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.

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 6
    No, `sys.modules[__name__]` is *exactly* right. – Martijn Pieters Dec 12 '13 at 22:15
  • 1
    You may want to read [PEP 395](http://www.python.org/dev/peps/pep-0395/), 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.) – abarnert Dec 12 '13 at 22:29
  • @abarnert Awesome, very informative. – Marcin Dec 12 '13 at 22:33
  • @sds In what way is this a duplicate? `globals()` is not the solution here. – Marcin Nov 15 '16 at 16:20
  • @Marcin: wrong link. this is a dupe of http://stackoverflow.com/q/1676835/850781 – sds Nov 15 '16 at 16:24

1 Answers1

8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343