1

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) ?

2
  • You don't want much, do you? Commented Feb 7, 2013 at 14:18
  • Why can't you use from a import *? Commented Feb 7, 2013 at 14:23

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

13 Comments

In fact i don't want to import all names from a, just some of them (depending on their type). I'll try your solution, but i thought there was a "safer" alternative to updating globals()
@ibi0tux: It is not at all clear why using x = a.x and such is not something you can do. Dynamically adding names to your namespace requires manipulating globals() or using exec, and I cannot recommend the latter when globals() will do.
Actually the module is imported with zipimport and i have something like : a = zipimport . zipimporter ( "archive.zip" ) mod_a = a . load_module ( "test" ) # considering archive.zip contains a module test print mod_a . value # considering value is defined in module test Is there any way to make the import directly in global ?
@ibi0tux: See, why didn't you post than in your question to start with? You can just add the zip module to your sys.path and import normally.
Does this mean i don't need to use zipimport ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.