How to print a module name in Python? - python

How do you print a module name in Python?
I tried to import a module and print it, then it gives me <module 'time' (built-in)>.
import time
print(time) # <module 'time' (built-in)>
How to print just the module name?

The name of a module as a string is available as its __name__ attribute.
>>> import time
>>> print(time.__name__)
time
This is shown in the Tutorial, by the way.

Simply import a module and print its name using _name

Related

Why do *import ...* and *from x import y* idioms behave so differently here?

I have a package structure like this:
- src
- src/main.py
- src/package1
- src/package1/__init__.py
- src/package1/module1.py
- src/package1/module2.py
... where module2 is a subclass of module1, and therefore module1 gets referenced by an absolute import path in module2.py.
That is, in src/package1/module2.py:
from package1.module1 import SomeClassFromModule1
The problem occurs in the main.py script:
## here the imports
def main():
# create an instance of the child class in Module2
if __name__ == "__main__":
main()
Option 1 works. That is, in src/main.py:
from package1.module2 import SomeClassFromModule2
some_name = SomeClassFromModule2()
Option 2 does not work. That is, in src/main.py:
import package1.module2.SomeClassFromModule2
some_name = package1.module2.SomeClassFromModule2()
... causes the following error.
ModuleNotFoundError: No module named 'package1.module2.SomeClassFromModule2'; 'package1.module2' is not a package
So why is there this difference between the import and from ... import idiom?
Would be glad for some clarification.
import x keyword brings all the methods and class from x in the the file it is being called.
from x import y this brings a specific method or class('y' is a method or class) from that .py file ('x' is the file here) instead of bringing all the methods it has.
In your case when you import package1.module2 the SomeClassForModule2() is being already imported and hence you need not write import package1.module2.SomeClassFromModule2
here I guess you want to access a class, so you need to create a object in order to access it.
hope this helped you
After some test, I think you cannot import a function or class by using import your_module.your_class.
It's all about package, module, function and class:
# import module
>>>import os
<module 'os' from ooxx>
#use module of module (a litte weird)
>>>os.path
<module 'posixpath' from ooxx>
#import module of module (a litte weird)
>>>import os.path
#use function
>>>os.path.dirname
<function posixpath.dirname(p)>
# you cannot import a function (or class) by using 'import your.module.func'
# 'import ooxx' always get a module or package.
>>>import os.path.dirname
ModuleNotFoundError
No module named 'os.path.dirname'; 'os.path' is not a package
# instead of it, using 'from your_module import your_function_or_class'
>>>from os.path import dirname
<function posixpath.dirname(p)>

Python Namespaces and Modules

If I import a python module using a syntax like this:
import my_module
I can later use a number of simplest command to get an idea of what the module is, where it is located and etc. For example:
print(my_module)
outputs: module 'my_module' from 'my_module.py'
dir(my_module)
outputs: ['MyClass', 'builtins', 'doc', 'file', 'name', 'package', 'math', 'os', 'sys']
I even can find out an absolute path of the module by using:
print os.path.abspath( my_module.__file__ )
outputs: /Users/julia/Documents/classes/my_module.py
But if instead of import 'my_module' I would be using:
from my_module import MyClass
all I can is to:
print MyClass
which outputs: my_module.MyClass
I do see MyClass came from my_module file. But unfortunately that is all I can get since none of the commands I used to use to get the info on module doesn't work. Here is use and their output:
print dir(my_module.MyClass) NameError: name 'my_module' is not defined
print dir(my_module) NameError: name 'my_module' is not defined
print my_module name 'my_module' is not defined
What command(-s) should I be using while tracking down the imported modules brought with
from my_module import MyClass
syntax?
The Problem is that
from my_module import MyClass
only imports MyClass but not the whole Module.
If you want to know the name of the Module MyClass was imported from, you can use:
print MyClass.__module__
If you want to use other Stuff from the same Module you could use:
my_module = __import__(MyClass.__module__)
print dir(my_module)
But it would be far more easy to just write:
import my_module
Thanks Mr.Crash!
Here is the summary:
If the module was imported with:
from my_module import MyClass
don't call the module by using its name directly.
Instead get to it via class imported from this module (using class's module attr) such as:
print dir(MyClass.__module__)
print os.path.abspath( MyClass.__module__ )

Do something every time a module is imported

Is there a way to do something (like print "funkymodule imported" for example) every time a module is imported from any other module? Not only the first time it's imported to the runtime or reloaded?
One possibility would be to monkey patch __import__:
>>> old_import = __import__
>>> def my_import(module,*args,**kwargs):
... print module, 'loaded'
... return old_import(module,*args,**kwargs)
...
>>> __builtins__.__import__ = my_import
>>> import datetime
datetime loaded
>>> import datetime
datetime loaded
>>> import django
django loaded
It worked fine on command line (using Python 2.7.3 on Windows XP), but I dunno if would work in other environments.
To access the module object (instead of just the module name - so you can do something useful with it) just intercept the return value instead of the argument:
>>> def my_import(*args,**kwargs):
... ret = old_import(*args,**kwargs)
... print ret
... return ret
...
>>> __builtins__.__import__ = my_import
>>> import datetime
<module 'datetime' (built-in)>
>>> import django
<module 'django' from 'C:\Python27\lib\site-packages\django\__init__.pyc'>
Update: Just confirmed it works if used inside a python file too - though in this case, the correct way of assigning it is __builtins__['__import__'] = my_import.

Python: import modules dynamically in different namespace

import v_framework as framework
framework.loadModules(["Maintenance"])
framework.Maintenance.showPage()
In framework I have:
def loadModules(aModules):
d_utility = {"Maintenance":"COOl_M_PAGE"}
for module in a_aModules:
exec("import " + d_utility[module] + " as " + module)
When loadModules is executed, it imports the modules in the v_framework namespace. Since I am importing v_framework as framework, I think I should be able to use the imported module using framework.Maintenance. But it does not work that way.
Is there a way to do way to do what I'm trying to do? Alternatively, is there any way to import modules in a namespace other than the one where exec is executed?
There are libraries for importing modules dynamically. You could use importlib (and another one that might be useful is pkgutil). Now, for your case, I guess this would do the job:
import importlib
mods = {}
def loadModules(aModule):
global mods
mods[module] = importlib.import_module(d_utility[module])
# or maybe globals()[module] = ... would work also (exactly as you expect it to
UPDATE: exec modifies the function's local namespace, not the global one (I think).
Hope it helps. :)
When you import inside a function, the module is imported/executed as normal, but the name you import under is local to the function, just like any other variable assigned inside a function.
>>> def test_import():
... import os
... print os
...
>>> test_import()
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
os has been imported though, and you can still access it through sys.modules:
>>> import sys
>>> sys.modules['os']
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> os = sys.modules['os']
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>
A quick and dirty way to do what you want would be something like this; exec takes an optional mapping to be used as the local and global variables. So you could do
def loadModules(aModules):
d_utility = {"Maintenance":"COOl_M_PAGE"}
for module in aModules:
exec ('import %s as %s' % (d_utility[module], module)) in globals()
Though this is ugly and probably has security implications or something. As jadkik94 mentions, there are libraries that provide cleaner ways to deal with this.

Dynamic Importing in Python (Dotted statments)

I'm having trouble with the following code:
def get_module(mod_path):
mod_list = mod_path.split('.')
mod = __import__(mod_list.pop(0))
while mod_list:
mod = getattr(mod, mod_list.pop(0))
return mod
When I do get_module('qmbpmn.common.db_parsers') I get the error message:
AttributeError: 'module' object has no attribute 'db_parsers'.
However: import qmbpmn.common.db_parsers works perfectly fine.
When using __import__ to import submodules, you must pass the parent package as the fromlist argument:
>>> __import__("os.path")
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> __import__("os.path", fromlist=["os"])
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
__import__ works with the dotted module path, so this should work
def get_module(mod_path):
return __import__(mod_path)
or more simply
get_module = __import__
Perhaps I am misunderstanding the problem
importing a package does not automatically import all the submodules into it's namespace. For example
import qmbpmn
does not mean that
qmbpmn.common.db_parsers
will automatically resolve

Categories

Resources