Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override namespace in Python

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.

like image 413
Art Avatar asked Jul 08 '09 05:07

Art


People also ask

What is a namespace in Python?

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.

What is __ all __ in Python?

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.

What are the three types of namespaces in Python?

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.

How do you import a namespace in Python?

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.


1 Answers

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:

  • imp — Access the import internals
like image 59
ars Avatar answered Sep 19 '22 20:09

ars