9

If I wanted to get the current module, e.g. to reload it, I would do:

import sys sys.modules[__name__] 

Is there a better way to do this (e.g. not involving __name__)? Better in this context means more idiomatic, more portable, more robust, or more...any of the other things we usually desire in our software.

I use python 2, but answers for python 3 will no doubt be useful to others.

6
  • 6
    No, sys.modules[__name__] is exactly right. Commented Dec 12, 2013 at 22:15
  • 1
    You may want to read PEP 395, which describes all of the known traps/problems with __name__, and explains why there are no better alternatives that can avoid any of them in Python as it is today (3.4—and of course it's even more true for 2.7). (Despite the title, it proposed a few related changes, not just adding __qualname__, like a special metapath hook to make __main__ and the real module name act equivalent.) Commented Dec 12, 2013 at 22:29
  • @abarnert Awesome, very informative. Commented Dec 12, 2013 at 22:33
  • 1
    @Marcin: wrong link. this is a dupe of stackoverflow.com/q/1676835/850781 Commented Nov 15, 2016 at 16:24
  • 1
    Does this answer your question? How to get a reference to a module inside the module itself? Commented Mar 4, 2024 at 14:45

1 Answer 1

11

There is no more idiomatic method to get the current module object from sys.modules than what you used.

__name__ is set by Python on import, essentially doing:

module_object = import_py_file(import_name) module_object.__name__ = import_name sys.modules[import_name] = module_object 

so the __name__ reference is exactly what you want to use here.

Sign up to request clarification or add additional context in comments.

1 Comment

Just FWIW: one might not expect this to work from the "main" module (where the script was started, and thus __name__ == '__main__') - but it does. That module indeed gets stored as sys.modules['__main__']. (It could appear a second time, under its "real name", if it tries to import itself.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.