1

I'm a beginner to python, and have written a module that looks something like this:

# filename: mymodule.py
import numpy as np
from datetime import datetime
def a():
   ...<stuff>...
def b():
   ...<stuff>...

The consensus in this thread generally (and in agreement with PEP8) seems to be that import statements should be at the file header. However, now when I import mymodule, running dir(mymodule) shows that objects np and datetime are part of mymodule -- which offhand, seems inefficient and "sloppy". It seems one way to preserve only classes and defs would be some kind of conditional deletion via dynamic iteration over globals() (which after trying and failing for a bit, seems really elusive), or just use the del keyword on everything.


The main question: can I do this, and can I do this dynamically instead of explicitly? Don't the defs work independently, regardless of whether the header modules are part of the import? Otherwise from <x> import <y> would break every time, I would think.

Community
  • 1
  • 1
Luke Davis
  • 2,548
  • 2
  • 21
  • 43
  • Why do you think having other modules is inefficient? – Daniel Roseman Feb 18 '17 at 08:27
  • Isn't it just sort of messy? I guess that's my main gripe. What I mean is, say I have in some python script `import mymodule as my; import numpy as np`. Now there are two copies of `numpy` taking up memory -- `numpy` and `mymodule.np`. Although I suppose it's a very small amount of space. – Luke Davis Feb 18 '17 at 08:37
  • No. Both `numpy` and `mymodule.np` refer to the same entry in `sys.modules`. – Daniel Roseman Feb 18 '17 at 09:04
  • ...oh. I forgot that I don't know anything about anything. Thanks. – Luke Davis Feb 18 '17 at 09:07
  • @DanielRoseman So is this just accepted practice, to let the external module reference propagate into a separately imported module? It seems to me that this is not the "correct way", because importing standard libraries like `sys`, `os`, and `numpy` shows there are not alien module names in `dir(np)`, `dir(os)`, etc. Maybe this works by, for any file with lots of `class`es and `def`s, **always** using name-explicit `from x import y`s in the `__init__.py` file? – Luke Davis Feb 21 '17 at 20:48

0 Answers0