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.
hasattr() and sys.modules to build a structure which would keep track of it. But you'd have to have an attribute to test for each module you'd expect to have and even having such a correlation probably wouldn't be worth the effort of making it