0

Quick question:

from x import y, z

Is there any way that I can access the name of x within the script?

I know that if I look at the locals() or globals() dict, that I can see y and z, but I can't seem to find a way to look for x.

Matthew
  • 1,179
  • 2
  • 12
  • 16
  • `y.__module__` should return `"x"`, but I suppose you want to access the module object itself, not its name. – Frédéric Hamidi Nov 27 '15 at 13:45
  • 4
    What's a practical example of why you'd want to access `x`? – deceze Nov 27 '15 at 13:45
  • I have two modules: A.py and B.py. A.py contains `from x import y`. B.py contains `from x import z`. The `x` module must be added to the path, and so I use `sys.path.insert(1, x)`, but I only want to do this once. I trying to find a way to check in B.py if `x` has been loaded. – Matthew Nov 27 '15 at 13:53
  • 1
    Very much sounds like an [XY problem](http://meta.stackexchange.com/q/66377/476). Essentially you want to avoid `sys.path.insert` completely, and especially conditionally setting it, and instead set the `PYTHONPATH` in your environment correctly; completely obsoleting the entire question. – deceze Nov 27 '15 at 13:58
  • 1
    Don't worry if a module is already loaded, python check it automatically: [how to test if one python module has been imported?](http://stackoverflow.com/questions/5027352/how-to-test-if-one-python-module-has-been-imported) – k4ppa Nov 27 '15 at 13:58
  • 1
    Thank you all for the answers so far. I intentionally tried to abstract the main problem because it is just messy. I've asked another question not too long ago [here](https://stackoverflow.com/questions/33956594/better-solution-than-if-name-main-twice-in-python-script). Essentially, there are many versions of module `x` and this module has no fixed location. On different users machines, they must supply the directory, leading to this issue. The complexity comes with docopt mentioned in the original question, though beyond the scope of this one. – Matthew Nov 27 '15 at 14:08

1 Answers1

2

you need to also import x in that case. It's not a weird thing to do in my opinion.

Neil G
  • 32,138
  • 39
  • 156
  • 257