Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting What Module Was Imported As

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?

like image 417
pacman Avatar asked May 01 '26 07:05

pacman


1 Answers

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.

like image 51
user2357112 supports Monica Avatar answered May 02 '26 21:05

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!