Package: ultraimport
ultraimportGet control over your imports -- no matter how you run your code.Warning: This is an early hack. There are only few unit tests, yet. Maybe not stable!Overview|Installation|Quickstart|DocumentationOverviewFeaturesImport any file from the file system as Python code:Works independent of yoursys.pathWorks independent of your current working directoryWorks independent of your top-level packageWorks no matter if you run your code as a module or as a scriptDoes not care about __init__.py filesCan use relative or absolute pathesDynamically wrap your code in a virtual namespace packagePreprocess code for optimizations (seeexample)Recursively rewrite subsequent relative import statements (seeexample)Dependency injection (seeexample)Lazy loading (lazy imports for modules and callables)Fix circular imports through lazy imports or dependency injectionFix the error:ImportError: attempted relative import with no known parent packageFix the error:ValueError: attempted relative import beyond top-level packageBetter error messagesGeneral Approachultraimport is built around an own implementation of theimportlib.machinery.SourceFileLoader. This allows to take a different approach on finding code while still being compatible and integrate nicely with the normal Python import machinery. It also allows for some advanced use cases like virtual namespaces, pre-processing, lazy loading, dependency injection and last but not least much better error messages.Is ultraimport supposed to replace the normal import statement?No! You will continue to use the builtin import statements to import 3rd party libraries which have been installed system wide.ultraimportis meant to import local files whose locations you control because they are located relatively to some other files.IssuesCurrently, there is no integration with any Python language server for code completion in your IDE. Code completion in the Python REPL works as expected.InstallationInstall system wide:pipinstallultraimportInstall a local development version:gitclonehttps://github.com/ronny-rentner/ultraimport.git
pipinstall-e./ultraimportQuickstartNote: You can find this quickstart example and others in theexamples/folder.Thequickstartfolder looks like this:quickstart
├── cherry.py
├── readme.md
├── red
│   ├── cherry.py
│   └── strawberry.py
├── run
│   └── run.py
└── yellow
    ├── banana.py
    └── lemon.pyThe entry point is the scriptrun.pylocated in thequickstart/runfolder.
If you want, you can directly execute the example script by running:python/path/to/quickstart/run/run.pyInside therun.pyscript, first we import ultraimport:importultraimport1) Import from parent folderThis example shows how to import the Python modulecherry.pyfrom the parent folder. Note that__dir__in the file path refers to the parent folder of the file that is executing the import. In this case,run.pyis executing the import and it is located in a folderrunand thus__dir__refers to therunfolder.cherry=ultraimport('__dir__/../cherry.py')# <module 'cherry' from '/home/ronny/Projects/py/ultraimport/examples/quickstart/cherry.py'>2) Import from sibling folderThis exmaple show how to import another Python module from a sibling folder.other_cherry=ultraimport('__dir__/../red/cherry.py')# <module 'cherry' from '/home/ronny/Projects/py/ultraimport/examples/quickstart/red/cherry.py'>3) Import single objectImport theCherryobject fromcherry.pyand alias it to the namemy_class. You could also provide a list of strings
instead of a single string if you want to import multiple objects.my_class=ultraimport('__dir__/../red/cherry.py','Cherry')# <class 'cherry.Cherry'>4) Ensure type of imported objectYou can make suremy_classis actually the type you expect, a class, andmy_stringis a string, otherwise aTypeErroris thrown.my_class,my_string=ultraimport('__dir__/../cherry.py',{'MyClass':type,'some_string':str})# <class 'cherry.MyClass'>, "I am a string"5) Import all objectsUsing the known special string'*'allows to import all objects.objs=ultraimport('__dir__/../cherry.py','*')# <class 'cherry.MyClass'>6) Add imported objects to a namespaceYou can also provide any dict as a namespace. A common value to use isglobals(). If you setadd_to_ns=True,
the imported objects are added to the local scope of the caller.ultraimport('__dir__/../cherry.py','*',add_to_ns=globals())# <class 'cherry.MyClass'>7) Give imported module a known parent packageThe next import would fail because the importedbanana.pycontains another
relative import in line 1:from .. import cherry as relatively_imported_cherry.try:banana=ultraimport('__dir__/../yellow/banana.py')exceptExceptionase:# <class 'ultraimport.ultraimport.ExecuteImportError'>passIf you would try to excutebanana.pydirectly, you'd get the famousImportError: attempted relative import with no known parent packageerror. To solve
this error, just give thebanana.pymodule a known parent package by using thepackageparameter.
The relative import from above has two dots, so it means go two levels up. Thus we need to
give ourbanana.pymodule at least two levels of parent packages by usingpackage=2.banana=ultraimport('__dir__/../yellow/banana.py',package=2)# <module 'quickstart.yellow.banana' from '/home/ronny/Projects/py/ultraimport/examples/quickstart/yellow/banana.py'>8) Embed module in a virtual namespace packageYou can also provide a string for thepackageparameter to define the name of the package. In this case
we create a package calledfruitpointing at the parent directory ofcherry.py, the file that is being
imported.cherry=ultraimport('__dir__/../red/cherry.py',package='some.fruit')# <module 'some.fruit.cherry' from '/home/ronny/Projects/py/ultraimport/examples/quickstart/red/cherry.py'>9) Integrate with normal importsAfter creating thefruitnamespace package as a side effect of the import, you can use it to do classical imports.
Remember that thefruitpackage points to the directoryred.fromsome.fruit.strawberryimportStrawberry# <class 'some.fruit.strawberry.Strawberry'>10) Create virtual namespace packageYou could also explicitly create a virtual namespace pointing to the directory'yellow'. Note that__dir__in the path below refers to the parent folder of the file that is executing the import.yellow_ns=ultraimport.create_ns_package('yellow','__dir__/../yellow')# <module 'yellow' (<_frozen_importlib_external._NamespaceLoader object at 0x7fba8de36920>)>For further imports, the package_nameyellowmust be used as provided as the first argument.fromyellowimportlemon# <module 'yellow.lemon' from '/home/ronny/Projects/py/ultraimport/examples/quickstart/yellow/lemon.py'>Let's add some other modulecherry.pyfrom a different directory to our virtual package. After
you have added the module to the package, you can again use normal Python imports
to access it.ultraimport('__dir__/../red/cherry.py',package='yellow')fromyellow.cherryimportCherry# <class 'yellow.cherry.Cherry'>DocumentationThefull interface documentationcan be find in thedocs/folder. This is just an excerpt of the main function.ultraimportfunction:link: sourceultraimport(file_path,objects_to_import=None,add_to_ns=None,preprocessor=None,package=None,caller=None,use_cache=True,lazy=False,recurse=False,inject=None,use_preprocessor_cache=True,cache_path_prefix=None)Import Python code files from the file system. This is the central main function of ultraimport.Parameters:file_path(str):  Path to the module file that should be imported. It can have any file extension. Please be aware that you must provide the file extension. The path can be relative or absolute. You can use the special string__dir__to refer to the directory of the caller. If run from a Python REPL, the current working directory will be used for__dir__. If you use advanced debugging tools (or want to save some CPU cycles) you might want to setcaller=__file__.objects_to_import(str | (Iterable[str] | Dict[str, object]):  Can have several modes depending on the type of the parameter.(str): Name of a single object to import from the module infile_path. The special value'*'selects all objects from that module.(Iterable[str]): A list of names of objects to import.(Dict[str, object]): The keys represent the names of the objects to import. The values define the expected types of those objects. ATypeErroris thrown if the types don't match the expectation. If you setlazy=True, you must use a dict forobjects_to_importand define the types.add_to_ns(Dict[str, object]):  add theobjects_to_importto the dict provided. Usually called withadd_to_ns=locals()if you want the imported module to be added to the global namespace of the caller.preprocessor(callable):  Takes the source code as an argument and can return a modified version of the source code. Check out thedebug-transform exampleon how to use the preprocessor.package(str | int):  Can have several modes depending on if you provide a string or an integer. If you provide a string, ultraimport will generate one or more namespace packages and use it as parent package of your imported module. If you set an integer, it means the number of path parts (directories) to extract from thefile_pathto calculate the namespace package. This can help with subsequent relative imports in your imported files. Ifpackageis set to the defaultNone, the module will be imported without setting it parent__package__.use_cache(bool):  If set toFalse, allows re-importing of the same source file even if it was imported before. Otherwise a cached version of the imported module is returned.lazy(bool):ExperimentalwipIf set toTrueand ifobjects_to_importis set toNone, it will lazy import the module. If set to True andobjects_to_importis a dict, the values of the dict must be the type of the object to lazy import from the module. Currently only the typecallableis supported.recurse(bool):  If set toTrue, a built-in preprocessor is activated to transparently rewrite all relative import statements (those with a dot likefrom . import something) to ultraimport() calls. Use this mode if you have no control over the source code of the impored modules.cache_path_prefix(str):  Directory for storing preprocessed files. If you use the preprocessor feature or if you use the optionrecurse=True(which in turn uses the preprocessor feature) you will have the option to store the resulting code after preprocessing. By default, they are stored in parallel to the original source code files, but this option allows to override to location. One common setting iscache_path_prefix='__pycache__'to store the processed files along with the bytecode files._Note_:  Even when you change this directory, this will be hidden from Python. Towards Python, the preprocessed files will always look like they are in the same directory as the original source code files, even if they are not.Returns:Depending on the parametersreturns one of the following:object:  Ifobjects_to_importisNone, returns a single module object.object:  Ifobjects_to_importis astr, returns the single object with the specified name from the imported module.dict:  Ifobjects_to_importhas the value'*', returns a dict of all items from the imported module.list:  Ifobjects_to_importis aList[str], return a list of imported objects from the imported module.Advanced UsageSeedocs/advanced-usage.mdBetter Error MessagesSeedocs/better-error-messages.mdContributingWe love contributions!ultraimport is open source, built on open source, and we'd love to have you hang out in our community.The Issue: Relative Imports in PythonClassically, to do a relative import, your Python scriptrun.pywould look like this if you wanted to import
theloggerobject from alogging.pymodule in the same directory:from.loggingimportloggerdefmain():# do somethinglogger('I did something')if__name__=='main':main()If you try to run the program in usual way, you'll get an error message:$python./run.py
Traceback(mostrecentcalllast):File"/home/user/myprogram/./run.py",line1,in<module>from.loggingimportlogger
ImportError:attemptedrelativeimportwithnoknownparentpackagePython programs or scripts can be executed in a number of different ways and surprisingly, with some of the ways, it even works:# Brokenpython~/myprogram/run.py# Workscd~
python-c'import myprogram.run'# Workspython-mmyprogram.run# Brokencd~/myprogram
python-c'import run'# Brokenpython-mrun# Brokenpython./run.py# Broken~/myprogram/run.pyYou wonder: Why does Python come to a different conclusion depending on the way how I run the program?The errorImportError: attempted relative import with no known parent packageis rather erratic because the code has never changed. Sometimes you would also getValueError: attempted relative import beyond top-level package.There actuallyisa known parent package. It's the directory where the code lives in.
Sometimes Python can see it, sometimes not.Even if there was no parent package, what's the issue with importing a module that
I only know from its relative position to my current module?With ultraimport your programrun.pywill always findlogging.pyin the same directory,
no matter how you run it. You could change it to look like this:#!/usr/bin/env python3# ultraimport needs to be installed and imported in the classical wayimportultraimport# Import the 'logger' object from 'logging.py' that is located in the same# directory as this file.# Note: `__dir__` refers to the directory where this file is in.logger=ultraimport('__dir__/logging.py','logger')defmain():# do somethinglogger('I did something')if__name__=='__main__':main()else:logger('I was imported')As you can see, you'll have to import ultraimport in the classical way. It's intended to be installed as a system-wide library.
Afterwards, you can import your own code based on relative or absolute file system paths so it can always be found.With ultraimport, Python code can be executed in an way and the imports keep working:# Workspython~/myprogram/run.py# Workscd~
python-c'import myprogram.run'# Workspython-mmyprogram.run# Workscd~/myprogram
python-c'import run'# Workspython-mrun# Workspython./run.py# Works~/myprogram/run.pyPython Relative Import Limitationshttps://peps.python.org/pep-0328/#relative-imports-and-nameRelative imports use a module'snameattribute to determine that module's position in the package hierarchy.
If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports
are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.