choco install -y python
--pre
option: choco install -y python --pre
choco upgrade -y python # or choco upgrade -y python --pre
.
(rather than /
).
__path__
attribute are also a package. __init__.py
)
__init__.py
) sys.modules
. __builtins__
is a module that is loaded when a Python interpreter is started up: >>> type(__builtins__) <class 'module'>
dir()
(which itself is located in the __builtins__
module): >>> __builtins__.dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', ' len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
ns.ident
to refer to ident
in namespace ns
. Innermost (local) scope | This scope contains the local names |
Scopes of call-chain | If an identifier is not found in the innermost scope, the interpreter tries to resolve them by going up the call-chain (call-stack, if you will) |
Current module's global names | If still not found, the current module's global names are tried. This is also the scope where globally declared names live. |
__builtins__ | As a last resort, the __builtins__ (and others?) namespace is searched. |
global
or nonlocal
statement, all identifiers are created in the namespace that is associated with the local scope, notably by assigning a value to non existing name or when using the import
statement. from MODULE import *
: it places the identifiers of MODULE in the global namespace. '__main__'
. del()
statement. (TODO: can they also be removed with the delattr()
built-in function?) sys.argv
: import sys if len(sys.argv) < 4: print('Script expected at least three arguments') sys.exit(-1) # # Script name is in sys.argv[0]. # Save value and remove from list: # scriptName = sys.argv[0] del sys.argv[0] print('Arguments that were passed to ' + scriptName + ':') for arg in sys.argv: print(' - ' + arg)
ENCODING-NAME
, for example cp1252
) with the following first line (after the optional shebang) in a source file # -*- coding: ENCODING-NAME -*-
.pyd
files are Python DLLs. Such files can be imported with import xyz
(without stating the .pyd
suffix). This DLL must be located in a directory that is pointed at with the PYTHONPATH
environment variable(?) in order to be found. .pyd
file must export a PyInit_xyz()
function (xyz
corresponds to the filename). unsigned char
to be 8-bit (as per comment in Python.h
) Lib/site.py
is automatically imported. This module appends site-specific paths to the module search path. # # http://stackoverflow.com/a/531327/180275 # class AAA(object): x = 1 class BBB(AAA): pass class CCC(BBB): pass print AAA.x, BBB.x, CCC.x # 1 1 1 BBB.x = 2 print AAA.x, BBB.x, CCC.x # 1 2 2 AAA.x = 3 print AAA.x, BBB.x, CCC.x # 3 2 2 a = AAA() print a.x, AAA.x # 3 3 a.x = 4 print a.x, AAA.x # 4 3
# # http://stackoverflow.com/a/4403680/180275 # # Compare with exception_handling_intended.py try: int("z") except IndexError, ValueError: print "exception"; # not caught!
# # http://stackoverflow.com/a/4403680/180275 # # Compare with exception_handling_unintended.py try: int("y") except (IndexError, ValueError): print "exception"
# # http://stackoverflow.com/a/530577/180275 # some_list = ['foo', 'bar', 'baz' ] some_other_list = ['one', 'two', 'three'] print "some_list" for item in some_list: print item # foo # bar # baz print "some_other_list" for iten in some_other_list: # note the typo: "iten" instead of "item" print item # baz # baz # baz
# # http://stackoverflow.com/a/531376/180275 # funcs = [] for x in range(5): funcs.append(lambda: x) print [f() for f in funcs] # [4, 4, 4, 4, 4] # --- funcs = [] for x in range(5): funcs.append(lambda x=x: x) print [f() for f in funcs] # [0, 1, 2, 3, 4]
#!/usr/bin/python3 # # http://stackoverflow.com/a/530768/180275 # import time def report_time_wrong(when=time.time()): print (when) report_time_wrong() # 1544219102.503972 time.sleep(5) # Note, same time again report_time_wrong() # 1544219102.503972 def report_time_better(when=None): if when is None: when = time.time() print (when) report_time_better() # 1544219107.5091524 time.sleep(5) report_time_better() # 1544219112.5136003
Lib/site-packages
directory (for example using unzip
, although a specialized installer (such as pip?) is recommended). --platform
command line option of pip install
.
distutils
) - but see also PEP 517 a, b, c, d = 3.1, 2.4, 1.9, 4.1 x = 4 y = a * x**3 + b * x**2 + c * x**1 + d * x**0
y = a * x**3 + \ b * x**2 + \ c * x**1 + \ d * x**0