Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?
Maybe some clever hacks in init.py?
Added:
It needs to be global - that is, other scripts loading 'project' via the standard:
import project
Have to work properly, loading a40bd22344 instead.
Namespaces in Python. A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves.
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
There are three types of Python namespaces- global, local, and built-in. It's the same with a variable scope in python. Also, the 'global' keyword lets us refer to a name in a global scope.
Importing is a way of pulling a name from somewhere else into the desired namespace. To refer to a variable, function, or class in Python one of the following must be true: The name is in the Python built-in namespace. The name is the current module's global namespace.
Here's one way to do it, without touching sys.path, using the imp
module in Python:
import imp
f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])
project = imp.load_module('a40bd22344', f, filename, desc)
project.some_func()
Here is a link to some good documentation on the imp
module:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With