I'm able to import a module from a directory with importlib, but I can't seem to utilize the classes correctly.
Without importlib, I can import the class as follows:
>>> from PySide2.QtWidgets import QApplication
>>> app = QApplication()
>>> print(app)
<PySide2.QtWidgets.QApplication object at 0x7fe3af6a9080>
But when I try to import it using importlib (which is needed for my dynamic imports), I get the following:
>>> import sys
>>> import importlib.util
>>> package_path = '/var/tmp/PySide2/__init__.py'
>>> spec = importlib.util.spec_from_file_location('PySide2.QtWidgets.QApplication', package_path)
>>> QApplication = importlib.util.module_from_spec(spec)
>>> sys.modules[spec.name] = QApplication
>>> spec.loader.exec_module(QApplication)
>>>
>>> app = QApplication()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
How can I get QApplication to behave the same as it does with from PySide2.QtWidgets import QApplication?
I tried some things with importlib.import_module and getattr(module, class), but I haven't been able to understand how to use import_module to import a module from a specific path in the filesystem.
I'm using Python 3.5
EDIT
I've also tried the following:
>>> package_path = '/var/tmp/PySide2/__init__.py'
>>> spec = importlib.util.spec_from_file_location('PySide2', package_path)
>>> PySide2 = importlib.util.module_from_spec(spec)
>>> sys.modules[spec.name] = PySide2
>>> spec.loader.exec_module(PySide2)
>>>
>>> app = PySide2.QtWidgets.QApplication()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'PySide2' has no attribute 'QtWidgets'
and
>>> QtWidgets = getattr(PySide2, 'QtWidgets')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'PySide2' has no attribute 'QtWidgets'
EDIT 2
Here are the top-level contents of the PySide2 directory, which was installed via python3 -m pip install PySide2==5.12.3, and the resulting PySide2 directory was then copied to /var/tmp/
_config.py Qt3DRender.pyi QtPositioning.pyi QtUiTools.pyi
examples QtCharts.abi3.so QtPrintSupport.abi3.so QtWebChannel.abi3.so
_git_pyside_version.py QtCharts.pyi QtPrintSupport.pyi QtWebChannel.pyi
glue QtConcurrent.abi3.so QtQml.abi3.so QtWebEngine.abi3.so
include QtConcurrent.pyi QtQml.pyi QtWebEngineCore.abi3.so
__init__.py QtCore.abi3.so QtQuick.abi3.so QtWebEngineCore.pyi
libpyside2.abi3.so.5.12 QtCore.pyi QtQuick.pyi QtWebEngine.pyi
__pycache__ QtDataVisualization.abi3.so QtQuickWidgets.abi3.so QtWebEngineWidgets.abi3.so
PySide QtDataVisualization.pyi QtQuickWidgets.pyi QtWebEngineWidgets.pyi
PySide2 QtGui.abi3.so QtRemoteObjects.abi3.so QtWebSockets.abi3.so
pyside2-lupdate QtGui.pyi QtRemoteObjects.pyi QtWebSockets.pyi
pyside2-rcc QtHelp.abi3.so QtScxml.abi3.so QtWidgets.abi3.so
Qt QtHelp.pyi QtScxml.pyi QtWidgets.pyi
Qt3DAnimation.abi3.so QtLocation.abi3.so QtSensors.abi3.so QtX11Extras.abi3.so
Qt3DAnimation.pyi QtLocation.pyi QtSensors.pyi QtX11Extras.pyi
Qt3DCore.abi3.so QtMultimedia.abi3.so QtSql.abi3.so QtXml.abi3.so
Qt3DCore.pyi QtMultimedia.pyi QtSql.pyi QtXmlPatterns.abi3.so
Qt3DExtras.abi3.so QtMultimediaWidgets.abi3.so QtSvg.abi3.so QtXmlPatterns.pyi
Qt3DExtras.pyi QtMultimediaWidgets.pyi QtSvg.pyi QtXml.pyi
Qt3DInput.abi3.so QtNetwork.abi3.so QtTest.abi3.so scripts
Qt3DInput.pyi QtNetwork.pyi QtTest.pyi support
Qt3DLogic.abi3.so QtOpenGL.abi3.so QtTextToSpeech.abi3.so typesystems
Qt3DLogic.pyi QtOpenGL.pyi QtTextToSpeech.pyi
Qt3DRender.abi3.so QtPositioning.abi3.so QtUiTools.abi3.so
I think you're messing up the definition of modules. While from PySide2.QtWidgets is a module (file), QApplication is a definition inside of this module (a class definition).
To use import_module, you must give the path to the module. This will return a module object (as in import PySide2.QtWidgets as module). You can then use the module as you wish :)
Example:
import importlib
module = importlib.import_module('PySide2.QtWidgets')
QApplication = module.QApplication
app = QApplication()
Definition of package
Definition of module
Definition of importing
To import from a specific location, you can do almost as you did in the question (Importing a source file directly):
import importlib.util
# Note that I'm using the module path, not the package path
module_path = '/var/tmp/PySide2/QtWidgets.py'
spec = importlib.util.spec_from_file_location('PySide2.QtWidgets', module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
QApplication = module.QApplication
app = QApplication()
Related
I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.
What is so special about ldap.modlist that I have to explicitly import it? Importing ldap is not enough:
>>> import ldap
>>> ldap.modlist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'modlist'
But if I explicitly import it, then all is well:
>>> import ldap
>>> import ldap.modlist
>>> ldap.modlist
<module 'ldap.modlist' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/modlist.pyc'>
Why? Other modules don't behave like this:
>>> import os
>>> os.path
<module 'posixpath' from '/opt/rh/python27/root/usr/lib64/python2.7/posixpath.pyc'>
>>> import ldap
>>> ldap.dn
<module 'ldap.dn' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/dn.pyc'>
The difference between the modules ldap.dn and ldap.modlist is this:
The module ldap.dn is loaded during the initialization of the ldap package and is therefore already present as an attribute in the ldap package (see The Import System: Submodules for a description about submodules):
# ldap/__init__.py, line 89 of python-ldap version 2.4.27
from ldap.dn import explode_dn,explode_rdn,str2dn,dn2str
The module ldap.modlist on the other hand is not loaded during the initalization of the ldap package.
I recently installed a library in Python 3.3.2. I tried to import a module from it like this: import cx_Freeze.freezer. However, cx_Freeze.freezer is not defined as I would have expected, as shown in IDLE:
>>> ================================ RESTART ================================
>>> import cx_Freeze.freezer
>>> cx_Freeze.freezer
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
cx_Freeze.freezer
AttributeError: 'module' object has no attribute 'freezer'
>>>
The same thing happens in the command line. I think I am misunderstanding what happens when you use import with dot notation; what name does the module get assigned to?
In order to fix this seeming problem, I tried import cx_Freeze.freezer as f after restarting the shell, but that gave the same error as before. Can someone please explain why these import statements aren't giving me access to the module?
cx_Freeze/__init__.py has the following contents:
version = "5.0"
import sys
from cx_Freeze.dist import *
if sys.platform == "win32":
from cx_Freeze.windist import *
elif sys.platform == "darwin":
from cx_Freeze.macdist import *
from cx_Freeze.finder import *
from cx_Freeze.freezer import *
from cx_Freeze.main import *
del dist
del finder
del freezer
The parts important to this question are from cx_Freeze.freezer import * and del freezer. The first of those lines imports everything listed in cx_Freeze.freezer.__all__ directly into the cx_Freeze package, and the second line makes cx_Freeze.freezer not available directly. Thus, you should probably just use cx_Freeze; it contains all the parts of cx_Freeze.freezer designed for external use. If you need cx_Freeze.freezer, perhaps to use some of the private functionality, you can find it in sys.modules:
import sys
freezer = sys.modules['cx_Freeze.freezer']
I have a package named 'package'within that i have modules module1.py and module2.py i imported the package as
import package
from package import module1
In module1 i have a function named funcwhenever i import that function as
from module1 import func
and use it, the function as
module1.func(x)
it doesn't work
What is the problem and what should be done??
You can do either:
from module1 import func
func(x)
OR
module1.func(x)
Real world example which should demonstrate how things work:
>>> import os
>>> os.path.abspath("C:/Documents")
'C:\\Documents'
>>>
>>> from os import path
>>> path.abspath("C:/documents")
'C:\\documents'
>>>
>>> from path import abspath
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named path
>>>
>>> from os.path import abspath
>>> abspath("C:/documents")
'C:\\documents'
You can either import as:
from foo import bar
bar(baz)
or:
import foo
foo.bar(baz)
In certain cases, it may also be helpful to:
from foo import bar as qux
qux(baz
There is an extensive tutorial on handling imports available as well.
2 options:
from package.module1 import func
func(x)
2nd option:
from package import module1
module1.func(x)
I want to get the path and source code of the __builtin__ module, where can I get it?
Latest (trunk) C sources of __builtin__ module: http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup
The __builtin__ module is built-in, there is no Python source for it. It's coded in C and included as part of the Python interpreter executable.
You can't. it is built-in to the interpreter.
>>> # os is from '/usr/lib/python2.7/os.pyc'
>>> import os
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> # PyQt4 is from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'
>>> import PyQt4
>>> PyQt4
<module 'PyQt4' from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'>
>>> # __builtin__ is built-in
>>> import __builtin__
>>> __builtin__
<module '__builtin__' (built-in)>
In a program, you could use the __file__ attribute, but built-in modules do not have it.
>>> os.__file__
'/usr/lib/python2.7/os.pyc'
>>> PyQt4.__file__
'/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'
>>> __builtin__.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'