Imports awareness in Imported modules problem
gagsl-py2 at yahoo.com.ar
Sun Aug 24 21:47:41 CEST 2008
En Sun, 24 Aug 2008 07:34:41 -0300, Mohamed Yousef <harrrrpo at gmail.com> escribió:
> On Sun, Aug 24, 2008 at 9:59 AM, Fredrik Lundh <fredrik at pythonware.com> wrote:
>> Mohamed Yousef wrote:
>>> why am i doing this in the first place
>>> I'm in the process of a medium project where imports of modules start
>>> to make a jungle and i wanted all needed imports to be in a single
>>> file (namely __init__.py)
>>> and then all imports are made once and other modules feel it
>> Python doesn't use a global namespace -- importing a given module into one
>> module doesn't make it visible everywhere else (and trust me, this is a very
>> good thing).
> why isn't it a good thing (even if optional)
> consider the sitution in which a utility module is used every where
> else - other modules -
> you may say import it in them all ,
Yes. That way, when you see a name "foo" used in a module, you can look at the imports to see where it comes from. (BTW, this is why using "from module import *" is not a good idea)
Having a single global namespace is a lot worse.
> what i changed it's name ? go back
> change all imports... this doesn't seem good
Yes. How often do you change the module's name? You may use an alias if you want to be backwards compatible.
> and what about package wide varailbles ?
If pkgA is a package, and you define a variable foo in its __init__.py, it is available as pkgA.foo - does it count as a "package wide variable"?
>>> my goal is basically making W() aware of the re module when called
>>> from A
>> to do that, add "import re" to the top of the C module.
> and sys ,string.. etc add them all twice or four / n times ?
Every module has its own namespace, it contains its own set of imports, unrelated to others.
If you want to use the re, or sys, or string modules - import them. As F.L. has already pointed, a module is loaded from disk only the first time it is imported; subsequent imports find the module in sys.modules and do nothing.
> remove one and then forget to remove one of them in a file and start
> debugging ... this really doesn't look to be a good practice
Why is that? Importing an otherwise unused module is usually just a performance problem - at least for well-behaving modules that don't have side effects on import.
More information about the Python-list