When starting the interactive Python interpreter with default
settings, is there any module implicitly imported/loaded into the
interpreter, without explicitly running import <modulename>?
I thought that modules like sys or builtins would be, but when I
type their module names,
>>> sys
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> builtins
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'builtins' is not defined
So is it correct that by default, there is no module imported/loaded implicitly?
When executing a python script, is there any module implicitly
imported/loaded into the script, without explicitly specifying
import <modulename> in the script?
Thanks.
One module that is usually imported automatically is site.py. And it imports a lot of other modules. But even if you prevent it from importing using option -S Python still imports many modules. Try the following script:
#! /usr/bin/python2.7 -ESs
import sys
print(sys.modules)
and see how many modules are there. Change shebang to
#! /usr/bin/python3 -EISs
and say "Wow!" :-)
Only __builtins__:
#! /usr/bin/python2.7 -ESs
print(dir())
=> ['__builtins__', '__doc__', '__file__', '__name__', '__package__']
Related
I've started playing around with pygame and pythonw recently, however whenever I attempt to import a majority of modules pythonw either imports incomplete modules or fails to import entirely.
All of the importing errors involve a Expected in: Flat Namespace
error with one of the many .so files in my conda3 python directory, which led me to believe that they were being loaded incorrectly by python or that they were broken; however, the modules all imported correctly in regular python.
I've ruled out the pythonw being located in a directory with nonexistent modules, as running sys.path in python and pythonw returns the same list.
Example of error, with the default-loaded help() command in Python(w) idle:
>>> help()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda3/lib/python3.6/_sitebuiltins.py", line 102, in __call__
import pydoc
File "/anaconda3/lib/python3.6/pydoc.py", line 63, in <module>
import platform
File "/anaconda3/lib/python3.6/platform.py", line 116, in <module>
import sys, os, re, subprocess
File "/anaconda3/lib/python3.6/subprocess.py", line 136, in <module>
import _posixsubprocess
ImportError: dlopen(/anaconda3/lib/python3.6/lib-dynload/_posixsubprocess.cpython-36m-darwin.so, 2): Symbol not found: __Py_set_inheritable_async_safe
Expected in: flat namespace
Referenced from: /anaconda3/lib/python3.6/lib-dynload/_posixsubprocess.cpython-36m-darwin.so
In the case of pygame, modules such as font are loaded incorrectly and instead replaced with pygame.MissingModule objects
>>> pygame
<module 'pygame' from '/anaconda3/lib/python3.6/site-packages/pygame/__init__.py'>
>>> pygame.font
<pygame.MissingModule object at 0x10e8b5400>
>>>
Does anyone have any idea what is happening here? Any help would be greatly appreciated!
EDIT: [1]: https://i.stack.imgur.com/jDBrB.jpg
Question
What does the following line do in Python 3?
>>> from . import *
What I found out so far...
It does not output anything and the only change I can see in Python 3.7.3 is the following:
>>> '__warningregistry__' in locals()
False
>>> from . import *
>>> '__warningregistry__' in locals()
True
>>> locals()['__warningregistry__']
{'version': 0}
This might be part of the warnings module and indicates that there is a warning somewhere which is not printed, but the documentation mentions only a variable __warningregistry__ in the the module warnings.
The documentation explains how from . import foo works, and how from bar import * works, but I couldn't find anything about from . import *. One might expect that all names from __init__.py are loaded into the current name space (as from bla import * would do for bla.py) but this doesn't seem to be the case and also it doesn't make sense when __name__ == '__main__' (scripts and terminal).
Python 2 behaves more similar to what I had expected:
>>> # Python 2.7.16
>>> from . import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
PEP 328 is quite illuminative but doesn't answer my question either.
When __main__ is a script or interactive session, . is the __main__ package itself:
$ python3 -c 'from . import float'
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name 'float' from '__main__' (unknown location)
This makes from . import * a noop, with __warningregistry__ added as a side-effect of the import machinery.
Relative imports from __main__ were special-cased by PEP 366. This introduced __package__ for relative package name lookup, and specifies that __main__. __package__ has the special value None.
In addition, the module import spec __main__.__spec__ may be None - namely in an interactive shell or when executing a script.
As it turns out, any module with __package__ = __spec__ = None will treat . as itself:
$ cat test.py
__package__ = __spec__ = None
from . import float
$ python3 -c 'import test'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/mfischer/PycharmProjects/lispy/test.py", line 2, in <module>
from . import float
ImportError: cannot import name 'float' from 'test' (./test.py)
The __warningregistry__ is added because there is a hidden warning from the missing attributes. It is suppressed by default, but you can see it with all warning enabled:
$ python3 -Wa -c 'from . import float'
-c:1: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name 'float' from '__main__' (unknown location)
I am trying to import the importlib module but I get this message:
>>> importlib
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'importlib' is not defined
I have manually located the importlib file within the Python folder, so I know I have it. I am running Python version 3.4.1. I also tried to pip install importlib but it wasn't found either.
What's going on?
You need to use an import statement to load it in:
>>> import importlib
>>> importlib
<module 'importlib' from 'C:\\Python33\\lib\\importlib\\__init__.py'>
How can you find where python imported a particular module from?
Each module object has a __file__ attribute:
import module
print module.__file__
Some modules are part of the Python executable; these will not have the attribute set.
Demo:
>>> import urllib2
>>> urllib2.__file__
'/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.pyc'
>>> import sys
>>> sys.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
You could also run Python in verbose mode, with the -v command line switch or the PYTHONVERBOSE environment variable; Python then prints out every imported file as it takes place.
I have a problem when mocking in unittest.
#!/usr/bin/env python
import sys
sys.modules["foo.Bar"] = __import__("mock_bar")
import foo.Bar
print foo.Bar.__name__
I've got an ImportError exception in line 4. I don't know why since I have do some mock at line 3. There is a reference of how to mock import here.
Here's the error message:
Traceback (most recent call last):
File "test.py", line 4, in <module>
import foo.Bar
ImportError: No module named foo.Bar
"import foo.Bar" should equal to "__import__('foo.Bar')", and before that I've hacked sys.modules to pretend module 'foo.Bar' has been already imported. Why python still try to import foo.Bar and complain?
Try doing import foo before your __import__ line: I think it could help.