9
9
from functools import wraps
10
10
from typing import List , Type
11
11
12
- try :
13
- import rpy2
14
- import rpy2 .robjects
15
- except ImportError :
16
- pass
17
12
if sys .version_info >= (3 , 9 ):
18
13
from functools import cache
19
14
else :
20
15
from functools import lru_cache
16
+
21
17
cache = lru_cache (maxsize = None )
22
18
23
19
from packaging import version
@@ -357,45 +353,41 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
357
353
return isort .code (code = code , ** options )
358
354
359
355
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
363
361
364
362
@property
365
363
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 != ""
368
370
369
- rpackages .importr (self .package_name , robject_translations = {".env" : "env" })
370
371
371
- return True
372
- except Exception :
373
- return False
372
+ class FormatRFormatter ( RFormatter ):
373
+ label = "Apply FormatR Formatter"
374
+ package_name = "formatR"
374
375
375
376
@handle_line_ending_and_magic
376
377
def format_code (self , code : str , notebook : bool , ** options ) -> str :
378
+ # while not used, this import is needed to load conversion rules
379
+ import rpy2 .robjects
377
380
import rpy2 .robjects .packages as rpackages
378
381
379
382
format_r = rpackages .importr (self .package_name , robject_translations = {".env" : "env" })
380
383
formatted_code = format_r .tidy_source (text = code , output = False , ** options )
381
384
return "\n " .join (formatted_code [0 ])
382
385
383
386
384
- class StylerFormatter (BaseFormatter ):
387
+ class StylerFormatter (RFormatter ):
385
388
label = "Apply Styler Formatter"
386
389
package_name = "styler"
387
390
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
-
399
391
@handle_line_ending_and_magic
400
392
def format_code (self , code : str , notebook : bool , ** options ) -> str :
401
393
import rpy2 .robjects .packages as rpackages
@@ -407,6 +399,7 @@ def format_code(self, code: str, notebook: bool, **options) -> str:
407
399
@staticmethod
408
400
def _transform_options (styler_r , options ):
409
401
transformed_options = copy .deepcopy (options )
402
+ import rpy2 .robjects
410
403
411
404
if "math_token_spacing" in transformed_options :
412
405
if isinstance (options ["math_token_spacing" ], dict ):
0 commit comments