Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current python module object (by name or otherwise)

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.

like image 990
Marcin Avatar asked Oct 03 '22 04:10

Marcin


1 Answers

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.

like image 180
Martijn Pieters Avatar answered Oct 13 '22 12:10

Martijn Pieters