imp

see the python documentation about programmatic imports

Types

Utils

ImpItem

for aliasing items to import similar to item as alias

/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section Attributes
  else: warn(msg)

source

ImpItem

 ImpItem (item:str='')

A class to represent an item in the import specification.

Fallbacks


source

Fallbacks

 Fallbacks ()
Fallbacks.from_dict({'a': 1})
Fallbacks()
Fallbacks.from_items([
    ImpItem('os as py_os'),
    ImpItem('Tree as my_tree'),
]).items()
dict_items([('py_os', None), ('my_tree', None)])

BaseImp

for reducing code reuse


source

BaseImp

 BaseImp (namespace:Dict[str,Any]=<factory>)

Import Module class.

This class facilitates dynamic import of modules and their attributes.

ImpSubSpec


source

ImpSubSpec

 ImpSubSpec (name:str, stub:str,
             items:Optional[List[ForwardRef('ImpItem')]]=<factory>, fallba
             cks:Union[ForwardRef('Fallbacks'),Dict[str,Any],NoneType]=<fa
             ctory>, namespace:Dict[str,Any]=<factory>)

A class to represent a sub-specification of the import.

ImpSubSpec.from_str('from rich.tree import Tree as rich_tree')
ImpSubSpec(name='rich', stub='tree', items=[ImpItem(name='Tree', nick='rich_tree')])
ImpSubSpec('rich', '', [ImpItem('get_console')])
ImpSubSpec(name='rich', stub='', items=[ImpItem(name='get_console', nick='')])
ImpSubSpec.from_str('from rich import get_console')
ImpSubSpec(name='rich', stub='', items=[ImpItem(name='get_console', nick='')])

ImpSpec


source

ImpSpec

 ImpSpec (name:str, nick:Optional[str]=None, lazy:Optional[bool]=True,
          subspecs:Optional[List[ForwardRef('ImpSubSpec')]]=<factory>, fal
          lbacks:Union[ForwardRef('Fallbacks'),Dict[str,Any],NoneType]=<fa
          ctory>, namespace:Dict[str,Any]=<factory>)

A class to represent an import specification.

Imp

/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section Methods
  else: warn(msg)

source

Imp

 Imp (name:str, nick:Optional[str]=None,
      subspecs:Optional[List[__main__.ImpSubSpec]]=<factory>,
      fallbacks:Optional[Dict[str,Any]]=<factory>,
      lazy:Optional[bool]=True, delay:Optional[bool]=False,
      namespace:Dict[str,Any]=<factory>,
      _squash_name_errors:Optional[bool]=True,
      _reload:Optional[bool]=False)

Import Module class.

This class facilitates dynamic import of modules and their attributes.

Type Default Details
name str The name of the module to import.
nick Optional None The alias of the module to import.
subspecs Optional A list of ImpSubSpec objects representing additional specifications for import.
fallbacks Optional A dictionary of fallback values for import failures.
lazy Optional True Whether or not to use lazy import.
delay Optional False
namespace Dict
_squash_name_errors Optional True
_reload Optional False

Example

imp_rich = Imp(
    'rich', 'rc',
    subspecs=[
        ImpSubSpec.from_str('from rich.tree import Tree as rich_tree'),
        ImpSubSpec.from_str('from rich.text import Text'),
        ImpSubSpec.from_str('from rich.markup import espace'),
        ImpSubSpec.from_str('from rich.filesize import decimal'),
        ImpSubSpec.from_str('from rich.filesize import Console'),
        ImpSubSpec.from_str('from rich.progress import Progress'),
        # ImpSubSpec.from_str('from rich import get_console')
        ImpSubSpec('rich', '', [ImpItem('get_console')])
    ],
    fallbacks={
        'rich_tree': Any,
        'Text': Any,
    },
    delay=True,
)
Text
NameError: name 'Text' is not defined
imp_rich.load()
Imp(name='rich', nick='rc', lazy=True, delay=True, _squash_name_errors=True, _reload=False)
Text
rich.text.Text

Piecewise

# Define a sub specification to import 'sqrt' and 'pi' from 'math' module
subspec = ImpSubSpec('math', '', items=[ImpItem('sqrt'), ImpItem('sqrt')])
subspec
ImpSubSpec(name='math', stub='', items=[ImpItem(name='sqrt', nick=''), ImpItem(name='sqrt', nick='')])
# Create an Imp instance
imp = Imp(name='math', nick=None, subspecs=[subspec])

# Load the modules specified in the Imp instance
imp.load()

# Now you can access 'sqrt' and 'pi' from the 'math' module
sqrt = imp['sqrt']
pi = imp['pi']
print(sqrt(16))  # outputs: 4.0
print(pi)  # outputs: 3.141592653589793
4.0
3.141592653589793

Subclass Example

@dataclass
class MathImp(Imp):
    name: str = 'math'
    nick: str = 'm'
    subspecs: ImpSubSpecType = field(default_factory = lambda: [
        ImpSubSpec('math', '', [ImpItem('inf')]),
    ])
mimp = MathImp().load()
mimp._module
<module 'math' from '/Users/solst/mambaforge/envs/ipos/lib/python3.11/lib-dynload/math.cpython-311-darwin.so'>