Skip to content

Commit

Permalink
Delay rpy2 import until the formatter is requested
Browse files Browse the repository at this point in the history
Restore `rpy2.robjects` import
  • Loading branch information
krassowski committed Jul 15, 2024
1 parent 8e3ed8a commit 44c07c8
Showing 1 changed file with 19 additions and 26 deletions.
45 changes: 19 additions & 26 deletions jupyterlab_code_formatter/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@
from functools import wraps
from typing import List, Type

try:
import rpy2
import rpy2.robjects
except ImportError:
pass
if sys.version_info >= (3, 9):
from functools import cache
else:
from functools import lru_cache

cache = lru_cache(maxsize=None)

from packaging import version
Expand Down Expand Up @@ -357,45 +353,41 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
return isort.code(code=code, **options)


class FormatRFormatter(BaseFormatter):
label = "Apply FormatR Formatter"
package_name = "formatR"
class RFormatter(BaseFormatter):
@property
@abc.abstractmethod
def package_name(self) -> str:
pass

@property
def importable(self) -> bool:
try:
import rpy2.robjects.packages as rpackages
package_location = subprocess.run(
["Rscript", "-e", f"cat(system.file(package='{self.package_name}'))"],
capture_output=True,
text=True,
)
return package_location != ""

rpackages.importr(self.package_name, robject_translations={".env": "env"})

return True
except Exception:
return False
class FormatRFormatter(RFormatter):
label = "Apply FormatR Formatter"
package_name = "formatR"

@handle_line_ending_and_magic
def format_code(self, code: str, notebook: bool, **options) -> str:
# while not used, this import is needed to load conversion rules
import rpy2.robjects
import rpy2.robjects.packages as rpackages

format_r = rpackages.importr(self.package_name, robject_translations={".env": "env"})
formatted_code = format_r.tidy_source(text=code, output=False, **options)
return "\n".join(formatted_code[0])


class StylerFormatter(BaseFormatter):
class StylerFormatter(RFormatter):
label = "Apply Styler Formatter"
package_name = "styler"

@property
def importable(self) -> bool:
try:
import rpy2.robjects.packages as rpackages

rpackages.importr(self.package_name)

return True
except Exception:
return False

@handle_line_ending_and_magic
def format_code(self, code: str, notebook: bool, **options) -> str:
import rpy2.robjects.packages as rpackages
Expand All @@ -407,6 +399,7 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
@staticmethod
def _transform_options(styler_r, options):
transformed_options = copy.deepcopy(options)
import rpy2.robjects

if "math_token_spacing" in transformed_options:
if isinstance(options["math_token_spacing"], dict):
Expand Down

0 comments on commit 44c07c8

Please sign in to comment.