Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from ... import * with __import__ function [duplicate]

Tags:

python

import

Possible Duplicate:
from . import x using __import__?
How does one do the equivalent of import * from module with Python's __import__ function?

How would I do the from ... import * with the __import__ function? The reason being that i only know the name of the file at runtime and it only has 1 class inside that file.

like image 809
Pwnna Avatar asked Jul 22 '10 19:07

Pwnna


People also ask

What does __ import __ return?

Conclusion. The __import__() in python module helps in getting the code present in another module by either importing the function or code or file using the import in python method. The import in python returns the object or module that we specified while using the import module.

How does Python handle duplicate imports?

Yes, you can import module as many times as you want in one Python program, no matter what module it is. Every subsequent import after the first accesses the cached module instead of re-evaluating it.

What happens if I import the same module twice?

If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules. 1.

Why is Python running my module when I import it?

This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .


1 Answers

In case someone reading this wants an actual answer to the question in the title, you can do it by manipulating the vars() dictionary. Yes, it is dumb to do this in most scenarios, but I can think of use cases where it would actually be really useful/cool (e.g. maybe you want a static module name, but want the contents of the module to come from somewhere else that's defined at runtime. Similar to and, IMO, better than the behavior of django.conf.settings if you're familiar with it)

module_name = "foo"
for key, val in vars(__import__(module_name)).iteritems():
    if key.startswith('__') and key.endswith('__'):
        continue
    vars()[key] = val

This imports every non-system variable in the module foo.py into the current namespace.

Use sparingly :)

like image 61
danny Avatar answered Oct 12 '22 23:10

danny