Is there a way for a Python module to know what a user has imported it as?
For example, if the user does import myModule as foo, is there a way for code in myModule to know that the user import it as foo?
Nope. Python doesn't keep track of what names a module was imported by. Even if it did, a module can be imported by many names over the course of a program, but its code will only be executed on the first import, so it wouldn't get a chance to do anything about the new names.
I suppose if you want, you could tell it about the name:
# In mymodule
def register_name(name):
do_something_about(name)
# At the import site
import mymodule as foo
foo.register_name('foo')
Kind of unwieldy, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With