Python: import via function into main namespace

(Important: see update below.)

I am trying to write an import_something function that will be important for specific modules. (No matter what this refers to.) The fact is that I would like these modules to be imported at the level from which the function is being called. For instance:

 import_something() # Let say this imports my_module my_module.do_stuff() # 

Is it possible?

Update:

Sorry, my original phrase and example were misleading. I will try to explain my whole problem. I have a package in which there are several modules and packages. In __init__.py I want to import all modules and packages. Therefore, somewhere else in the program, I import the entire package and iterate over the modules / packages that it imported.

(Why? The package is called crunchers , and all types of crunchers are defined inside it, for example CruncherThread , CruncherProcess , and in the future MicroThreadCruncher possible. I want the crunchers package to automatically have all the clusters that are in it, so later in the program, when I use crunchers , I know that he can determine exactly which boxes he defined.)

I know that I can solve this problem, if I will not use functions at all, and do all the imports at the main level using for loops, etc. But this is ugly, and I want to see if I can avoid it.

If something else is unclear, ask in the comments.

+4
source share
4 answers

Functions can return something to where they were called. It is called the return value: p

 def import_something(): # decide what to import # ... mod = __import__( something ) return mod my_module = import_something() my_module.do_stuff() 

nice style, no hassle.

About your update, I think adding something like you __init__.py does what you want:

 import os # make a list of all .py files in the same dir that dont start with _ __all__ = installed = [ name for (name,ext) in ( os.path.splitext(fn) for fn in os.listdir(os.path.dirname(__file__))) if ext=='.py' and not name.startswith('_') ] for name in installed: # import them all __import__( name, globals(), locals()) 

in the other place:

 import crunchers crunchers.installed # all names crunchers.cruncherA # actual module object, but you can't use it since you don't know the name when you write the code # turns out the be pretty much the same as the first solution :p mycruncher = getattr(crunchers, crunchers.installed[0]) 
+4
source

You can monkey with a parent frame in CPython to install modules in the locale for this frame (and only for this frame). The downside is that a) it is really pretty hacky and b) sys._getframe () is not guaranteed in other python implementations.

 def importer(): f = sys._getframe(1) # Get the parent frame f.f_locals["some_name"] = __import__(module_name, f.f_globals, f.f_locals) 

You still need to install the module in f_locals, since the import doesn’t actually do this for you - you just supply the parent frame locales and globals for the right context.

Then in your calling function you can:

 def foo(): importer() # Magically makes 'some_name' available to the calling function some_name.some_func() 
+1
source

Are you looking for something like this?

 def my_import(*names): for name in names: sys._getframe(1).f_locals[name] = __import__(name) 

then you can call it like this:

 my_import("os", "re") 

or

 namelist = ["os", "re"] my_import(*namelist) 
+1
source

According to __import__ help:

 __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module Import a module. The globals are only used to determine the context; they are not modified. ... 

That way you can just get the globals of your parent frame and use it to call __import__ .

 def import_something(s): return __import__(s, sys._getframe(1).f_globals) 

Note: the signature of Pre-2.6, __import__ was different in that it simply had optional parameters instead of using kwargs. Since globals is the second argument in both cases, the method he named above works fine. You just need to know if you decide to use any of the other arguments.

0
source

All Articles