Skip to content

Commit 4226af8

Browse files
committed
Delay rpy2 import until the formatter is requested
1 parent 368d9ef commit 4226af8

File tree

1 file changed

+17
-26
lines changed

1 file changed

+17
-26
lines changed

jupyterlab_code_formatter/formatters.py

Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,11 @@
99
from functools import wraps
1010
from typing import List, Type
1111

12-
try:
13-
import rpy2
14-
import rpy2.robjects
15-
except ImportError:
16-
pass
1712
if sys.version_info >= (3, 9):
1813
from functools import cache
1914
else:
2015
from functools import lru_cache
16+
2117
cache = lru_cache(maxsize=None)
2218

2319
from packaging import version
@@ -357,20 +353,25 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
357353
return isort.code(code=code, **options)
358354

359355

360-
class FormatRFormatter(BaseFormatter):
361-
label = "Apply FormatR Formatter"
362-
package_name = "formatR"
356+
class RFormatter(BaseFormatter):
357+
@property
358+
@abc.abstractmethod
359+
def package_name(self) -> str:
360+
pass
363361

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

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

371-
return True
372-
except Exception:
373-
return False
372+
class FormatRFormatter(RFormatter):
373+
label = "Apply FormatR Formatter"
374+
package_name = "formatR"
374375

375376
@handle_line_ending_and_magic
376377
def format_code(self, code: str, notebook: bool, **options) -> str:
@@ -381,21 +382,10 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
381382
return "\n".join(formatted_code[0])
382383

383384

384-
class StylerFormatter(BaseFormatter):
385+
class StylerFormatter(RFormatter):
385386
label = "Apply Styler Formatter"
386387
package_name = "styler"
387388

388-
@property
389-
def importable(self) -> bool:
390-
try:
391-
import rpy2.robjects.packages as rpackages
392-
393-
rpackages.importr(self.package_name)
394-
395-
return True
396-
except Exception:
397-
return False
398-
399389
@handle_line_ending_and_magic
400390
def format_code(self, code: str, notebook: bool, **options) -> str:
401391
import rpy2.robjects.packages as rpackages
@@ -407,6 +397,7 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
407397
@staticmethod
408398
def _transform_options(styler_r, options):
409399
transformed_options = copy.deepcopy(options)
400+
import rpy2.robjects
410401

411402
if "math_token_spacing" in transformed_options:
412403
if isinstance(options["math_token_spacing"], dict):

0 commit comments

Comments
 (0)