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)
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)
When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:,The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:,A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. 1 (They are also run if the file is executed as a script.),This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end = ' ')
a, b = b, a + b
print()
def fib2(n): #
return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
>>>
import fibo
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>>
fibo.fib2(100)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>>
fibo.__name__ 'fibo'
>>> fib = fibo.fib >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> from fibo
import fib, fib2
>>>
fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> from fibo
import *
>>>
fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Last Updated : 26 Nov, 2020
Output:
35