How do I check if I imported a module somewhere in the code?
if not has_imported("somemodule"):
print('you have not imported somemodule')
The reason that I would like to check if I already imported a module is because I have a module that I don’t want to import, because sometimes it messes up my program.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Test for the module name in the sys.modules dictionary:
import sys
modulename = 'datetime'
if modulename not in sys.modules:
print 'You have not imported the {} module'.format(modulename)
From the documenation:
This is a dictionary that maps module names to modules which have already been loaded.
Note that an import statement does two things:
- if the module has never been imported before (== not present in
sys.modules), then it is loaded and added tosys.modules. - Bind 1 or more names in the current namespace that reference the module object or to objects that are members of the module namespace.
The expression modulename not in sys.modules tests if step 1 has taken place. Testing for the result of step 2 requires knowing what exact import statement was used as they set different names to reference different objects:
import modulenamesetsmodulename = sys.modules['modulename']import packagename.nestedmodulesetspackagename = sys.modules['packagename'](no matter how many addional levels you add)import modulename as altnamesetsaltname = sys.module['modulename']import packagename.nestedmodule as altnamesetsaltname = sys.modules['packagename.nestedmodule']from somemodule import objectnamesetsobjectname = sys.modules['somemodule'].objectnamefrom packagename import nestedmodulenamesetsnestedmodulename = sys.modules['packagename.nestedmodulename'](only when there was no object namednestedmodulenamein thepackagenamenamespace before this import, an additional name for the nested module is added to the parent package namespace at this point)from somemodule import objectname as altnamesetsaltname = sys.modules['somemodule'].objectnamefrom packagename import nestedmodulename as altnamesetsaltname = sys.modules['packagename.nestedmodulename'](only when there was no object namednestedmodulenamein thepackagenamenamespace before this import, an additional name for the nested module is added to the parent package namespace at this point)
You can test if the name to which the imported object was bound exists in a given namespace:
# is this name visible in the current scope: 'importedname' in dir() # or, is this a name in the globals of the current module: 'importedname' in globals() # or, does the name exist in the namespace of another module: 'importedname' in globals(sys.modules['somemodule'])
This only tells you of the name exists (has been bound), not if it refers to a specific module or object from that module. You could further introspect that object or test if it’s the same object as what’s available in sys.modules, if you need to rule out that the name has been set to something else entirely since then.
Method 2
To the sys.modules answers accepted, I’d add one caveat to be careful about renaming modules on import:
>>> import sys >>> import datetime as dt >>> 'dt' in sys.modules False >>> 'datetime' in sys.modules True
Method 3
Use sys.modules to test if a module has been imported (I’m using unicodedata as an example):
>>> import sys >>> 'unicodedata' in sys.modules False >>> import unicodedata >>> 'unicodedata' in sys.modules True
Method 4
sys.modules contains all modules used anywhere in the current instance of the interpreter and so shows up if imported in any other Python module.
dir() checks whether the name was defined in the current namespace.
The combination of the two is safer than each separate and works as long you didn’t define a copy yourself.
if ('copy' in sys.modules) and ('copy' in dir()):
Method 5
Use:
if "sys" not in dir():
print("sys not imported!")
This works well at the beginning (top) of the code, but it should be carefully used, in case another object with name sys is created.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0