Given imports like this:
from a.very.long.list.of.packages.aaa.bbb.ccc import abc
from a.very.long.list.of.packages.ddd.eee import de
from a.very.long.list.of.packages.fff import f
from a.very.long.list.of.packages import somepackage
is there any way to define aliases for the common part of the module path and reuse it?
I'm imagining something like this:
x = a.very.long.list.of.packages
from x.aaa.bbb.ccc import abc
from x.ddd.eee import de
from x.fff import f
from x import somepackage
Given x = a.very.long.list.of.packages, Python will try to resolve all the attributes and fail immediately because no name a has been defined. If it already exists, it's unlikely that it has the attribute very and the object this attribute points to has the attribute long and so on. Anyway, everything to the right of the assignment operator will be evaluated to some object, and it's not possible to import stuff from objects with from ... import ....
You can use dynamic importing with the built-in importlib module. It lets you treat strings as paths to modules.
Related
I know I can use importlib to import modules via a string. How can I recreate the import * functionality using this library? Basically, I want something like this:
importlib.import_module('path.to.module', '*')
My reasons for not name-spacing the imported attributes are deliberate.
Here is a solution: import the module, then one by one make alias in the current namespace:
import importlib
# Import the module
mod = importlib.import_module('collections')
# Determine a list of names to copy to the current name space
names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])
# Copy those names into the current name space
g = globals()
for name in names:
g[name] = getattr(mod, name)
Here is shorten version for #HaiVu answer which refers to this solution from #Bakuriu
import importlib
# import the module
mod = importlib.import_module('collections')
# make the variable global
globals().update(mod.__dict__)
Note:
This will import lots of things beside the user-defined variables
#HaiVu solution did the best of it ie. only import user-defined variables
i'm new to python. i've some python scripts where in need to import different python modules.
Is it possible to
import all modules to one single file, say modules.py
and import this modules.py to all scripts, so that no need to import modules to each script ?
Thanks in advance
In mymodules:
import module1
import module2
in app:
from mymodules import *
But is it really worth it? The Zen of python states:
Explicit is better than implicit.
Copying some lines at the top of a file isn't really too much trouble.
There are at least 4 Ways to Import a Module:
import X, imports the module X: this way you can use X.whatever to refer to things defined in module X.
from X import *, imports the module X: this way you can simply use a plain name to refer to things defined in module X.
from X import x, y, z: you can now use x and y and z in the current name space.
X = __import__(‘X’) works like import X but this time the module name is a string. Use it it you don't know the module name before execution.
Think about namespace as a Python dictionary structure, where the dictionary keys represent the names and the dictionary values the object itself. Using import you can name the module inside your namespace.
That's said, you can perfectly import the modules inside a script (name it importer os something), and then import "importer" and everything will be inside your namespace.
Is that a good idea?, probably no because is common to found the same name (method, function or whatever) inside different modules and if that happens then ambiguity appears.
My problem is quite easy but I can not find a good answer because the search engines are ambiguous on the term "module".
What I want do to is roughly this :
Module : a.py
x = 2
Module : b.py
import a
Now, I want to be able to access x from b without using qualified name (i.e. without typing a.x, just with x). In my situation I cannot use :
from a import x
because I don't know which elements a will contains. I can not use
from a import *
neither. Is there any simple way to merge or join the modules (I mean the Object Modules) ?
This is not a good idea, but you can use:
globals().update(vars(a))
to add all names defined in the a module to your local namespace. This is almost the same as from a import *. To emulate from a import * exactly, without using from a import * itself, you'd have to use:
globals().update(p for p in vars(a).items() if p[0] in getattr(a, '__all__', dir(a)))
You normally just would use x = a.x or from a import x.
If you are using zipimport you don't have to do any of this. Just add the path to the archive to your sys.path:
import sys
sys.path.insert(0, '/path/to/archive.zip')
from test import x
I have a long module name and I want to avoid having to type it all over many times in my document. I can simply do import long_ass_module_name as lamn and call it that way. However, this module has many submodules that I wish to import and use as well.
In this case I won't be able to write import lamn.sub_module_1 because python import does not recognize this alias I made for my long_ass_module_name. How can I achieve this?
Should I simply automatically import all submodules in my main module's __init__.py?
An aliased object still changes when you import submodules,
import my_long_module_name as mlmn
import my_long_module_name.submodule
mlmn.submodule.function()
The import statement always takes the full name of the module. The module is just an object, and importing a submodule will add an attribute to that object.
This (highly unrecommendable) way of importing all the members of an object to the current namespace works by looking up the vars() dictionary:
import my_bad_ass_long_module.bafd as b
# get __dict__ of current namespace
myn = vars()
for k,v in vars(b).items():
# populate this namespace with the all the members of the b namespace (overwriting!)
myn[k] = v
I am given a module as an object, and I need to import a submodule from it. Like this:
import logging
x = logging
Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.)
How do I do this? If I do import x.handlers it fails.
Try:
__import__('%s.handlers' % x.__name__)
Note that this will return a reference to logging, which you probably won't care about. It will create x.handlers though.
You can use built-in function __import__:
http://docs.python.org/library/functions.html#import