Hello World

[1]:
print('Hello World')
Hello World
[2]:
s = 'Mississippi'
print(s)
Mississippi
[3]:
s
[3]:
'Mississippi'
[4]:
s.count('ss')
[4]:
2
[5]:
s.index('ss')
[5]:
2
[6]:
import json
[7]:
d = {'eins': 1,
    'zwei': 2}
d['eins']
[7]:
1
[8]:
d_as_str = json.dumps(d)
[9]:
d_as_str
[9]:
'{"eins": 1, "zwei": 2}'
[10]:
received_d = json.loads(d_as_str)
[11]:
received_d
[11]:
{'eins': 1, 'zwei': 2}
[12]:
import subprocess
[13]:
subprocess.run(['ls', '-l'])
total 160
-rw-rw-r--. 1 jfasch jfasch   4926 Mar 30 10:57 index.rst
-rw-rw-r--. 1 jfasch jfasch   1939 Mar  1 17:00 index.rst.~1~
-rw-rw-r--. 1 jfasch jfasch 145415 Mar 30 11:16 Notebook.ipynb
-rw-rw-r--. 1 jfasch jfasch     72 Mar  1 16:38 notebook-wrapper.rst
[13]:
CompletedProcess(args=['ls', '-l'], returncode=0)
[14]:
i = 42
[15]:
print(i)
42
[16]:
type(i)
[16]:
int
[17]:
i = [1, 2, 3]
[18]:
type(i)
[18]:
list
[19]:
f = open('/etc/passwd')
[20]:
for line in f:
    line = line.rstrip('\n')
    fields = line.split(':')
    print(fields[0])
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
apache
systemd-network
systemd-coredump
systemd-resolve
systemd-oom
systemd-timesync
tss
dbus
polkitd
avahi
unbound
dnsmasq
nm-openconnect
usbmuxd
gluster
rtkit
pipewire
geoclue
chrony
saslauth
radvd
rpc
qemu
openvpn
nm-openvpn
colord
rpcuser
abrt
flatpak
gdm
gnome-initial-setup
vboxadd
sshd
tcpdump
jfasch
mosquitto
someone-else
[21]:
s
[21]:
'Mississippi'
[22]:
help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __getitem__(self, key, /)
 |      Return self[key].
 |
 |  __getnewargs__(...)
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __hash__(self, /)
 |      Return hash(self).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __le__(self, value, /)
 |      Return self<=value.
 |
 |  __len__(self, /)
 |      Return len(self).
 |
 |  __lt__(self, value, /)
 |      Return self<value.
 |
 |  __mod__(self, value, /)
 |      Return self%value.
 |
 |  __mul__(self, value, /)
 |      Return self*value.
 |
 |  __ne__(self, value, /)
 |      Return self!=value.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __rmod__(self, value, /)
 |      Return value%self.
 |
 |  __rmul__(self, value, /)
 |      Return value*self.
 |
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |
 |      Padding is done using the specified fill character (default is a space).
 |
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Return -1 on failure.
 |
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Raises ValueError when the substring is not found.
 |
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |
 |      Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
 |      such as "def" or "class".
 |
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |
 |      Padding is done using the specified fill character (default is a space).
 |
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |
 |      If chars is given and not None, remove characters in chars instead.
 |
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |
 |  removeprefix(self, prefix, /)
 |      Return a str with the given prefix string removed if present.
 |
 |      If the string starts with the prefix string, return string[len(prefix):].
 |      Otherwise, return a copy of the original string.
 |
 |  removesuffix(self, suffix, /)
 |      Return a str with the given suffix string removed if present.
 |
 |      If the string ends with the suffix string and that suffix is not empty,
 |      return string[:-len(suffix)]. Otherwise, return a copy of the original
 |      string.
 |
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Return -1 on failure.
 |
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Raises ValueError when the substring is not found.
 |
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |
 |      Padding is done using the specified fill character (default is a space).
 |
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |
 |        sep
 |          The delimiter according which to split the string.
 |          None (the default value) means split according to any whitespace,
 |          and discard empty strings from the result.
 |        maxsplit
 |          Maximum number of splits to do.
 |          -1 (the default value) means no limit.
 |
 |      Splits are done starting at the end of the string and working to the front.
 |
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |
 |      If chars is given and not None, remove characters in chars instead.
 |
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |
 |      sep
 |        The delimiter according which to split the string.
 |        None (the default value) means split according to any whitespace,
 |        and discard empty strings from the result.
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.
 |
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace removed.
 |
 |      If chars is given and not None, remove characters in chars instead.
 |
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |
 |      The string is never truncated.
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  maketrans(...)
 |      Return a translation table usable for str.translate().
 |
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

[23]:
s.center(50)
[23]:
'                   Mississippi                    '
[24]:
def add(l, r):
    '''
    Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,
    und bildet mit einem numerischen Algorithmus die Summe aus beiden.

    Diese Summe ist dann der Wert des Aufrufs.
    '''
    return l+r
[25]:
add(1, 2)
[25]:
3
[26]:
add.__doc__
[26]:
'\n    Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,\n    und bildet mit einem numerischen Algorithmus die Summe aus beiden.\n    \n    Diese Summe ist dann der Wert des Aufrufs.\n    '
[27]:
help(add)
Help on function add in module __main__:

add(l, r)
    Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,
    und bildet mit einem numerischen Algorithmus die Summe aus beiden.

    Diese Summe ist dann der Wert des Aufrufs.

[28]:
json
[28]:
<module 'json' from '/usr/lib64/python3.9/json/__init__.py'>
[29]:
help(json)
Help on package json:

NAME
    json

MODULE REFERENCE
    https://docs.python.org/3.9/library/json

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    JSON (JavaScript Object Notation) <http://json.org> is a subset of
    JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
    interchange format.

    :mod:`json` exposes an API familiar to users of the standard library
    :mod:`marshal` and :mod:`pickle` modules.  It is derived from a
    version of the externally maintained simplejson library.

    Encoding basic Python object hierarchies::

        >>> import json
        >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        '["foo", {"bar": ["baz", null, 1.0, 2]}]'
        >>> print(json.dumps("\"foo\bar"))
        "\"foo\bar"
        >>> print(json.dumps('\u1234'))
        "\u1234"
        >>> print(json.dumps('\\'))
        "\\"
        >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
        {"a": 0, "b": 0, "c": 0}
        >>> from io import StringIO
        >>> io = StringIO()
        >>> json.dump(['streaming API'], io)
        >>> io.getvalue()
        '["streaming API"]'

    Compact encoding::

        >>> import json
        >>> mydict = {'4': 5, '6': 7}
        >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
        '[1,2,3,{"4":5,"6":7}]'

    Pretty printing::

        >>> import json
        >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
        {
            "4": 5,
            "6": 7
        }

    Decoding JSON::

        >>> import json
        >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
        >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
        True
        >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
        True
        >>> from io import StringIO
        >>> io = StringIO('["streaming API"]')
        >>> json.load(io)[0] == 'streaming API'
        True

    Specializing JSON object decoding::

        >>> import json
        >>> def as_complex(dct):
        ...     if '__complex__' in dct:
        ...         return complex(dct['real'], dct['imag'])
        ...     return dct
        ...
        >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
        ...     object_hook=as_complex)
        (1+2j)
        >>> from decimal import Decimal
        >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
        True

    Specializing JSON object encoding::

        >>> import json
        >>> def encode_complex(obj):
        ...     if isinstance(obj, complex):
        ...         return [obj.real, obj.imag]
        ...     raise TypeError(f'Object of type {obj.__class__.__name__} '
        ...                     f'is not JSON serializable')
        ...
        >>> json.dumps(2 + 1j, default=encode_complex)
        '[2.0, 1.0]'
        >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
        '[2.0, 1.0]'
        >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
        '[2.0, 1.0]'


    Using json.tool from the shell to validate and pretty-print::

        $ echo '{"json":"obj"}' | python -m json.tool
        {
            "json": "obj"
        }
        $ echo '{ 1.2:3.4}' | python -m json.tool
        Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

PACKAGE CONTENTS
    decoder
    encoder
    scanner
    tool

CLASSES
    builtins.ValueError(builtins.Exception)
        json.decoder.JSONDecodeError
    builtins.object
        json.decoder.JSONDecoder
        json.encoder.JSONEncoder

    class JSONDecodeError(builtins.ValueError)
     |  JSONDecodeError(msg, doc, pos)
     |
     |  Subclass of ValueError with the following additional properties:
     |
     |  msg: The unformatted error message
     |  doc: The JSON document being parsed
     |  pos: The start index of doc where parsing failed
     |  lineno: The line corresponding to pos
     |  colno: The column corresponding to pos
     |
     |  Method resolution order:
     |      JSONDecodeError
     |      builtins.ValueError
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |
     |  Methods defined here:
     |
     |  __init__(self, msg, doc, pos)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  __reduce__(self)
     |      Helper for pickle.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
     |
     |  ----------------------------------------------------------------------
     |  Static methods inherited from builtins.ValueError:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.BaseException:
     |
     |  __delattr__(self, name, /)
     |      Implement delattr(self, name).
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __repr__(self, /)
     |      Return repr(self).
     |
     |  __setattr__(self, name, value, /)
     |      Implement setattr(self, name, value).
     |
     |  __setstate__(...)
     |
     |  __str__(self, /)
     |      Return str(self).
     |
     |  with_traceback(...)
     |      Exception.with_traceback(tb) --
     |      set self.__traceback__ to tb and return self.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from builtins.BaseException:
     |
     |  __cause__
     |      exception cause
     |
     |  __context__
     |      exception context
     |
     |  __dict__
     |
     |  __suppress_context__
     |
     |  __traceback__
     |
     |  args

    class JSONDecoder(builtins.object)
     |  JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
     |
     |  Simple JSON <http://json.org> decoder
     |
     |  Performs the following translations in decoding by default:
     |
     |  +---------------+-------------------+
     |  | JSON          | Python            |
     |  +===============+===================+
     |  | object        | dict              |
     |  +---------------+-------------------+
     |  | array         | list              |
     |  +---------------+-------------------+
     |  | string        | str               |
     |  +---------------+-------------------+
     |  | number (int)  | int               |
     |  +---------------+-------------------+
     |  | number (real) | float             |
     |  +---------------+-------------------+
     |  | true          | True              |
     |  +---------------+-------------------+
     |  | false         | False             |
     |  +---------------+-------------------+
     |  | null          | None              |
     |  +---------------+-------------------+
     |
     |  It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
     |  their corresponding ``float`` values, which is outside the JSON spec.
     |
     |  Methods defined here:
     |
     |  __init__(self, *, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
     |      ``object_hook``, if specified, will be called with the result
     |      of every JSON object decoded and its return value will be used in
     |      place of the given ``dict``.  This can be used to provide custom
     |      deserializations (e.g. to support JSON-RPC class hinting).
     |
     |      ``object_pairs_hook``, if specified will be called with the result of
     |      every JSON object decoded with an ordered list of pairs.  The return
     |      value of ``object_pairs_hook`` will be used instead of the ``dict``.
     |      This feature can be used to implement custom decoders.
     |      If ``object_hook`` is also defined, the ``object_pairs_hook`` takes
     |      priority.
     |
     |      ``parse_float``, if specified, will be called with the string
     |      of every JSON float to be decoded. By default this is equivalent to
     |      float(num_str). This can be used to use another datatype or parser
     |      for JSON floats (e.g. decimal.Decimal).
     |
     |      ``parse_int``, if specified, will be called with the string
     |      of every JSON int to be decoded. By default this is equivalent to
     |      int(num_str). This can be used to use another datatype or parser
     |      for JSON integers (e.g. float).
     |
     |      ``parse_constant``, if specified, will be called with one of the
     |      following strings: -Infinity, Infinity, NaN.
     |      This can be used to raise an exception if invalid JSON numbers
     |      are encountered.
     |
     |      If ``strict`` is false (true is the default), then control
     |      characters will be allowed inside strings.  Control characters in
     |      this context are those with character codes in the 0-31 range,
     |      including ``'\t'`` (tab), ``'\n'``, ``'\r'`` and ``'\0'``.
     |
     |  decode(self, s, _w=<built-in method match of re.Pattern object at 0x7f99fff1bb70>)
     |      Return the Python representation of ``s`` (a ``str`` instance
     |      containing a JSON document).
     |
     |  raw_decode(self, s, idx=0)
     |      Decode a JSON document from ``s`` (a ``str`` beginning with
     |      a JSON document) and return a 2-tuple of the Python
     |      representation and the index in ``s`` where the document ended.
     |
     |      This can be used to decode a JSON document from a string that may
     |      have extraneous data at the end.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)

    class JSONEncoder(builtins.object)
     |  JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
     |
     |  Extensible JSON <http://json.org> encoder for Python data structures.
     |
     |  Supports the following objects and types by default:
     |
     |  +-------------------+---------------+
     |  | Python            | JSON          |
     |  +===================+===============+
     |  | dict              | object        |
     |  +-------------------+---------------+
     |  | list, tuple       | array         |
     |  +-------------------+---------------+
     |  | str               | string        |
     |  +-------------------+---------------+
     |  | int, float        | number        |
     |  +-------------------+---------------+
     |  | True              | true          |
     |  +-------------------+---------------+
     |  | False             | false         |
     |  +-------------------+---------------+
     |  | None              | null          |
     |  +-------------------+---------------+
     |
     |  To extend this to recognize other objects, subclass and implement a
     |  ``.default()`` method with another method that returns a serializable
     |  object for ``o`` if possible, otherwise it should call the superclass
     |  implementation (to raise ``TypeError``).
     |
     |  Methods defined here:
     |
     |  __init__(self, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
     |      Constructor for JSONEncoder, with sensible defaults.
     |
     |      If skipkeys is false, then it is a TypeError to attempt
     |      encoding of keys that are not str, int, float or None.  If
     |      skipkeys is True, such items are simply skipped.
     |
     |      If ensure_ascii is true, the output is guaranteed to be str
     |      objects with all incoming non-ASCII characters escaped.  If
     |      ensure_ascii is false, the output can contain non-ASCII characters.
     |
     |      If check_circular is true, then lists, dicts, and custom encoded
     |      objects will be checked for circular references during encoding to
     |      prevent an infinite recursion (which would cause an RecursionError).
     |      Otherwise, no such check takes place.
     |
     |      If allow_nan is true, then NaN, Infinity, and -Infinity will be
     |      encoded as such.  This behavior is not JSON specification compliant,
     |      but is consistent with most JavaScript based encoders and decoders.
     |      Otherwise, it will be a ValueError to encode such floats.
     |
     |      If sort_keys is true, then the output of dictionaries will be
     |      sorted by key; this is useful for regression tests to ensure
     |      that JSON serializations can be compared on a day-to-day basis.
     |
     |      If indent is a non-negative integer, then JSON array
     |      elements and object members will be pretty-printed with that
     |      indent level.  An indent level of 0 will only insert newlines.
     |      None is the most compact representation.
     |
     |      If specified, separators should be an (item_separator, key_separator)
     |      tuple.  The default is (', ', ': ') if *indent* is ``None`` and
     |      (',', ': ') otherwise.  To get the most compact JSON representation,
     |      you should specify (',', ':') to eliminate whitespace.
     |
     |      If specified, default is a function that gets called for objects
     |      that can't otherwise be serialized.  It should return a JSON encodable
     |      version of the object or raise a ``TypeError``.
     |
     |  default(self, o)
     |      Implement this method in a subclass such that it returns
     |      a serializable object for ``o``, or calls the base implementation
     |      (to raise a ``TypeError``).
     |
     |      For example, to support arbitrary iterators, you could
     |      implement default like this::
     |
     |          def default(self, o):
     |              try:
     |                  iterable = iter(o)
     |              except TypeError:
     |                  pass
     |              else:
     |                  return list(iterable)
     |              # Let the base class default method raise the TypeError
     |              return JSONEncoder.default(self, o)
     |
     |  encode(self, o)
     |      Return a JSON string representation of a Python data structure.
     |
     |      >>> from json.encoder import JSONEncoder
     |      >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
     |      '{"foo": ["bar", "baz"]}'
     |
     |  iterencode(self, o, _one_shot=False)
     |      Encode the given object and yield each string
     |      representation as available.
     |
     |      For example::
     |
     |          for chunk in JSONEncoder().iterencode(bigobject):
     |              mysocket.write(chunk)
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
     |
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |
     |  item_separator = ', '
     |
     |  key_separator = ': '

FUNCTIONS
    dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
        Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
        ``.write()``-supporting file-like object).

        If ``skipkeys`` is true then ``dict`` keys that are not basic types
        (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
        instead of raising a ``TypeError``.

        If ``ensure_ascii`` is false, then the strings written to ``fp`` can
        contain non-ASCII characters if they appear in strings contained in
        ``obj``. Otherwise, all such characters are escaped in JSON strings.

        If ``check_circular`` is false, then the circular reference check
        for container types will be skipped and a circular reference will
        result in an ``RecursionError`` (or worse).

        If ``allow_nan`` is false, then it will be a ``ValueError`` to
        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
        in strict compliance of the JSON specification, instead of using the
        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

        If ``indent`` is a non-negative integer, then JSON array elements and
        object members will be pretty-printed with that indent level. An indent
        level of 0 will only insert newlines. ``None`` is the most compact
        representation.

        If specified, ``separators`` should be an ``(item_separator, key_separator)``
        tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
        ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
        you should specify ``(',', ':')`` to eliminate whitespace.

        ``default(obj)`` is a function that should return a serializable version
        of obj or raise TypeError. The default simply raises TypeError.

        If *sort_keys* is true (default: ``False``), then the output of
        dictionaries will be sorted by key.

        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
        ``.default()`` method to serialize additional types), specify it with
        the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

    dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
        Serialize ``obj`` to a JSON formatted ``str``.

        If ``skipkeys`` is true then ``dict`` keys that are not basic types
        (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
        instead of raising a ``TypeError``.

        If ``ensure_ascii`` is false, then the return value can contain non-ASCII
        characters if they appear in strings contained in ``obj``. Otherwise, all
        such characters are escaped in JSON strings.

        If ``check_circular`` is false, then the circular reference check
        for container types will be skipped and a circular reference will
        result in an ``RecursionError`` (or worse).

        If ``allow_nan`` is false, then it will be a ``ValueError`` to
        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
        strict compliance of the JSON specification, instead of using the
        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

        If ``indent`` is a non-negative integer, then JSON array elements and
        object members will be pretty-printed with that indent level. An indent
        level of 0 will only insert newlines. ``None`` is the most compact
        representation.

        If specified, ``separators`` should be an ``(item_separator, key_separator)``
        tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
        ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
        you should specify ``(',', ':')`` to eliminate whitespace.

        ``default(obj)`` is a function that should return a serializable version
        of obj or raise TypeError. The default simply raises TypeError.

        If *sort_keys* is true (default: ``False``), then the output of
        dictionaries will be sorted by key.

        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
        ``.default()`` method to serialize additional types), specify it with
        the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

    load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
        Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
        a JSON document) to a Python object.

        ``object_hook`` is an optional function that will be called with the
        result of any object literal decode (a ``dict``). The return value of
        ``object_hook`` will be used instead of the ``dict``. This feature
        can be used to implement custom decoders (e.g. JSON-RPC class hinting).

        ``object_pairs_hook`` is an optional function that will be called with the
        result of any object literal decoded with an ordered list of pairs.  The
        return value of ``object_pairs_hook`` will be used instead of the ``dict``.
        This feature can be used to implement custom decoders.  If ``object_hook``
        is also defined, the ``object_pairs_hook`` takes priority.

        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
        kwarg; otherwise ``JSONDecoder`` is used.

    loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
        Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
        containing a JSON document) to a Python object.

        ``object_hook`` is an optional function that will be called with the
        result of any object literal decode (a ``dict``). The return value of
        ``object_hook`` will be used instead of the ``dict``. This feature
        can be used to implement custom decoders (e.g. JSON-RPC class hinting).

        ``object_pairs_hook`` is an optional function that will be called with the
        result of any object literal decoded with an ordered list of pairs.  The
        return value of ``object_pairs_hook`` will be used instead of the ``dict``.
        This feature can be used to implement custom decoders.  If ``object_hook``
        is also defined, the ``object_pairs_hook`` takes priority.

        ``parse_float``, if specified, will be called with the string
        of every JSON float to be decoded. By default this is equivalent to
        float(num_str). This can be used to use another datatype or parser
        for JSON floats (e.g. decimal.Decimal).

        ``parse_int``, if specified, will be called with the string
        of every JSON int to be decoded. By default this is equivalent to
        int(num_str). This can be used to use another datatype or parser
        for JSON integers (e.g. float).

        ``parse_constant``, if specified, will be called with one of the
        following strings: -Infinity, Infinity, NaN.
        This can be used to raise an exception if invalid JSON numbers
        are encountered.

        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
        kwarg; otherwise ``JSONDecoder`` is used.

DATA
    __all__ = ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecod...

VERSION
    2.0.9

AUTHOR
    Bob Ippolito <bob@redivi.com>

FILE
    /usr/lib64/python3.9/json/__init__.py


Blahblah

Object Oriented?

[30]:
i = 42
[31]:
type(i)
[31]:
int
[32]:
l = [1, 'eins', 1.0]
type(l)
[32]:
list
[33]:
id(l)
[33]:
140299267714496
[34]:
l1 = []
[35]:
id(l1)
[35]:
140299267930496
[36]:
l.append('blah')
[37]:
l
[37]:
[1, 'eins', 1.0, 'blah']

MQTT

[38]:
import json
[39]:
schweissparameter_aussi = {
    'strom_ma': 200004,
    'spannung_v': 10000.01,
}
[40]:
aufs_kabel = json.dumps(schweissparameter_aussi)
aufs_kabel
[40]:
'{"strom_ma": 200004, "spannung_v": 10000.01}'
[41]:
# aufs_kabel: publish() nach mqtt, topic "maschine_112"
[42]:
# vom kabel, subscribe()d an mqtt, topic "maschine_112"
[43]:
vom_kabel = aufs_kabel
[44]:
schweissparameter_eini = json.loads(vom_kabel)
[45]:
schweissparameter_eini
[45]:
{'strom_ma': 200004, 'spannung_v': 10000.01}
[46]:
try:
    schweissparameter_eini['strom_a']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 'strom_a'

Syntax etc.

[47]:
a = 43
[48]:
if a == 42:
    print('jaja, eh 42')
    print(a)
print('fertig')
fertig
[49]:
a = 42; b = 666
[50]:
a
[50]:
42
[51]:
b
[51]:
666
[52]:
print('Hello', 'World')
Hello World
[53]:
print(


    'Hello',

    'World')
Hello World
[54]:
print('Hello', 'World', sep='***')
Hello***World
[55]:
'hallo'
[55]:
'hallo'
[56]:
"hallo"
[56]:
'hallo'
[57]:
s = "hal'lo"
[58]:
s[3]
[58]:
"'"
[59]:
s = 'hal"lo'
[60]:
s[3]
[60]:
'"'
[61]:
s = 'ha"ll\''
[62]:
s[2]
[62]:
'"'
[63]:
s[5]
[63]:
"'"
[64]:
s = '''das
ist
ein
multiline
string'''
[65]:
print(s)
das
ist
ein
multiline
string

Commandline Arguments

[66]:
import sys
[67]:
help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.9/library/sys

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules

    displayhook -- called to show results in an interactive session
    excepthook -- called to handle any uncaught exception other than SystemExit
      To customize printing in an interactive session or to install a custom
      top-level exception handler, assign other functions to replace these.

    stdin -- standard input file object; used by input()
    stdout -- standard output file object; used by print()
    stderr -- standard error object; used for error messages
      By assigning other file objects (or objects that behave like files)
      to these, it is possible to redirect all of the interpreter's I/O.

    last_type -- type of last uncaught exception
    last_value -- value of last uncaught exception
    last_traceback -- traceback of last uncaught exception
      These three are only available in an interactive session after a
      traceback has been printed.

    Static objects:

    builtin_module_names -- tuple of module names built into this interpreter
    copyright -- copyright notice pertaining to this interpreter
    exec_prefix -- prefix used to find the machine-specific Python library
    executable -- absolute path of the executable binary of the Python interpreter
    float_info -- a named tuple with information about the float implementation.
    float_repr_style -- string indicating the style of repr() output for floats
    hash_info -- a named tuple with information about the hash algorithm.
    hexversion -- version information encoded as a single integer
    implementation -- Python implementation information.
    int_info -- a named tuple with information about the int implementation.
    maxsize -- the largest supported length of containers.
    maxunicode -- the value of the largest Unicode code point
    platform -- platform identifier
    prefix -- prefix used to find the Python library
    thread_info -- a named tuple with information about the thread implementation.
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    __stdin__ -- the original stdin; don't touch!
    __stdout__ -- the original stdout; don't touch!
    __stderr__ -- the original stderr; don't touch!
    __displayhook__ -- the original displayhook; don't touch!
    __excepthook__ -- the original excepthook; don't touch!

    Functions:

    displayhook() -- print an object to the screen, and save it in builtins._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

FUNCTIONS
    __breakpointhook__ = breakpointhook(...)
        breakpointhook(*args, **kws)

        This hook function is called by built-in breakpoint().

    __displayhook__ = displayhook(object, /)
        Print an object to sys.stdout and also save it in builtins._

    __excepthook__ = excepthook(exctype, value, traceback, /)
        Handle an exception by displaying it with a traceback on sys.stderr.

    __unraisablehook__ = unraisablehook(unraisable, /)
        Handle an unraisable exception.

        The unraisable argument has the following attributes:

        * exc_type: Exception type.
        * exc_value: Exception value, can be None.
        * exc_traceback: Exception traceback, can be None.
        * err_msg: Error message, can be None.
        * object: Object causing the exception, can be None.

    addaudithook(hook)
        Adds a new audit hook callback.

    audit(...)
        audit(event, *args)

        Passes the event to any audit hooks that are attached.

    call_tracing(func, args, /)
        Call func(*args), while tracing is enabled.

        The tracing state is saved, and restored afterwards.  This is intended
        to be called from a debugger from a checkpoint, to recursively debug
        some other code.

    exc_info()
        Return current exception information: (type, value, traceback).

        Return information about the most recent exception caught by an except
        clause in the current stack frame or in an older stack frame.

    exit(status=None, /)
        Exit the interpreter by raising SystemExit(status).

        If the status is omitted or None, it defaults to zero (i.e., success).
        If the status is an integer, it will be used as the system exit status.
        If it is another kind of object, it will be printed and the system
        exit status will be one (i.e., failure).

    get_asyncgen_hooks()
        Return the installed asynchronous generators hooks.

        This returns a namedtuple of the form (firstiter, finalizer).

    get_coroutine_origin_tracking_depth()
        Check status of origin tracking for coroutine objects in this thread.

    getallocatedblocks()
        Return the number of memory blocks currently allocated.

    getdefaultencoding()
        Return the current default encoding used by the Unicode implementation.

    getdlopenflags()
        Return the current value of the flags that are used for dlopen calls.

        The flag constants are defined in the os module.

    getfilesystemencodeerrors()
        Return the error mode used Unicode to OS filename conversion.

    getfilesystemencoding()
        Return the encoding used to convert Unicode filenames to OS filenames.

    getprofile()
        Return the profiling function set with sys.setprofile.

        See the profiler chapter in the library manual.

    getrecursionlimit()
        Return the current value of the recursion limit.

        The recursion limit is the maximum depth of the Python interpreter
        stack.  This limit prevents infinite recursion from causing an overflow
        of the C stack and crashing Python.

    getrefcount(object, /)
        Return the reference count of object.

        The count returned is generally one higher than you might expect,
        because it includes the (temporary) reference as an argument to
        getrefcount().

    getsizeof(...)
        getsizeof(object [, default]) -> int

        Return the size of object in bytes.

    getswitchinterval()
        Return the current thread switch interval; see sys.setswitchinterval().

    gettrace()
        Return the global debug tracing function set with sys.settrace.

        See the debugger chapter in the library manual.

    intern(string, /)
        ``Intern'' the given string.

        This enters the string in the (global) table of interned strings whose
        purpose is to speed up dictionary lookups. Return the string itself or
        the previously interned string object with the same value.

    is_finalizing()
        Return True if Python is exiting.

    set_asyncgen_hooks(...)
        set_asyncgen_hooks(* [, firstiter] [, finalizer])

        Set a finalizer for async generators objects.

    set_coroutine_origin_tracking_depth(depth)
        Enable or disable origin tracking for coroutine objects in this thread.

        Coroutine objects will track 'depth' frames of traceback information
        about where they came from, available in their cr_origin attribute.

        Set a depth of 0 to disable.

    setdlopenflags(flags, /)
        Set the flags used by the interpreter for dlopen calls.

        This is used, for example, when the interpreter loads extension
        modules. Among other things, this will enable a lazy resolving of
        symbols when importing a module, if called as sys.setdlopenflags(0).
        To share symbols across extension modules, call as
        sys.setdlopenflags(os.RTLD_GLOBAL).  Symbolic names for the flag
        modules can be found in the os module (RTLD_xxx constants, e.g.
        os.RTLD_LAZY).

    setprofile(...)
        setprofile(function)

        Set the profiling function.  It will be called on each function call
        and return.  See the profiler chapter in the library manual.

    setrecursionlimit(limit, /)
        Set the maximum depth of the Python interpreter stack to n.

        This limit prevents infinite recursion from causing an overflow of the C
        stack and crashing Python.  The highest possible limit is platform-
        dependent.

    setswitchinterval(interval, /)
        Set the ideal thread switching delay inside the Python interpreter.

        The actual frequency of switching threads can be lower if the
        interpreter executes long sequences of uninterruptible code
        (this is implementation-specific and workload-dependent).

        The parameter must represent the desired switching delay in seconds
        A typical value is 0.005 (5 milliseconds).

    settrace(...)
        settrace(function)

        Set the global debug tracing function.  It will be called on each
        function call.  See the debugger chapter in the library manual.

    unraisablehook(unraisable, /)
        Handle an unraisable exception.

        The unraisable argument has the following attributes:

        * exc_type: Exception type.
        * exc_value: Exception value, can be None.
        * exc_traceback: Exception traceback, can be None.
        * err_msg: Error message, can be None.
        * object: Object causing the exception, can be None.

DATA
    __stderr__ = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf...
    __stdin__ = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8...
    __stdout__ = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf...
    abiflags = ''
    api_version = 1013
    argv = ['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/i...
    base_exec_prefix = '/usr'
    base_prefix = '/usr'
    builtin_module_names = ('_abc', '_ast', '_codecs', '_collections', '_f...
    byteorder = 'little'
    copyright = 'Copyright (c) 2001-2022 Python Software Foundati...ematis...
    displayhook = <ipykernel.displayhook.ZMQShellDisplayHook object>
    dont_write_bytecode = False
    exec_prefix = '/home/jfasch/venv/jfasch-home'
    executable = '/home/jfasch/venv/jfasch-home/bin/python'
    flags = sys.flags(debug=0, inspect=0, interactive=0, opt...ation=1, is...
    float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...
    float_repr_style = 'short'
    hash_info = sys.hash_info(width=64, modulus=2305843009213693...iphash2...
    hexversion = 50924272
    implementation = namespace(name='cpython', cache_tag='cpython-39'...xv...
    int_info = sys.int_info(bits_per_digit=30, sizeof_digit=4)
    maxsize = 9223372036854775807
    maxunicode = 1114111
    meta_path = [<class '_frozen_importlib.BuiltinImporter'>, <class '_fro...
    modules = {'IPython': <module 'IPython' from '/home/jfasch/venv/jfasch...
    path = ['/home/jfasch/work/jfasch-home/trainings/log/detail/2022-03-23...
    path_hooks = [<class 'zipimport.zipimporter'>, <function FileFinder.pa...
    path_importer_cache = {'/home/jfasch/.ipython': FileFinder('/home/jfas...
    platform = 'linux'
    platlibdir = 'lib64'
    prefix = '/home/jfasch/venv/jfasch-home'
    ps1 = 'In : '
    ps2 = '...: '
    ps3 = 'Out: '
    pycache_prefix = None
    stderr = <ipykernel.iostream.OutStream object>
    stdin = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
    stdout = <ipykernel.iostream.OutStream object>
    thread_info = sys.thread_info(name='pthread', lock='semaphore', versio...
    version = '3.9.10 (main, Jan 17 2022, 00:00:00) \n[GCC 11.2.1 20210728...
    version_info = sys.version_info(major=3, minor=9, micro=10, releaselev...
    warnoptions = []

FILE
    (built-in)


[68]:
sys.platform
[68]:
'linux'
[69]:
sys.executable
[69]:
'/home/jfasch/venv/jfasch-home/bin/python'
[70]:
sys.argv
[70]:
['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jfasch/.local/share/jupyter/runtime/kernel-2c445fb3-6ca4-4628-b9d9-7cfbbff55326.json']

Variables

[71]:
a = 42
type(a)
[71]:
int
[72]:
a = 1.5
type(a)
[72]:
float
[73]:
a = [1, 'eins']
type(a)
[73]:
list
[74]:
try:
    doesnt_exist
except Exception as e:
    print(type(e), e)
<class 'NameError'> name 'doesnt_exist' is not defined
[75]:
_a = 42
[76]:
_a666 = 666
[77]:
a = 1
b = 2
c = 3
[78]:
a
[78]:
1
[79]:
b
[79]:
2
[80]:
# ...
[81]:
a, b, c = 1, 2, 3
[82]:
a
[82]:
1
[83]:
b
[83]:
2
[84]:
# ...
[85]:
(a, b, c) = (1, 2, 3)
[86]:
a = b = c = 1
[87]:
a, b, c
[87]:
(1, 1, 1)

Assignment Details

[88]:
a = 42
[89]:
id(a)
[89]:
140299402960464
[90]:
b = a
[91]:
b
[91]:
42
[92]:
id(b)
[92]:
140299402960464

Datatypes

[93]:
i = 666
[94]:
i = 2**32-1
[95]:
i
[95]:
4294967295
[96]:
i = 2**64 - 1
[97]:
i
[97]:
18446744073709551615
[98]:
bin(2**64)
[98]:
'0b10000000000000000000000000000000000000000000000000000000000000000'
[99]:
2**10000
[99]:
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376

Floor division

[100]:
3/2    # == 1 in Python 2
[100]:
1.5
[101]:
3//2
[101]:
1

Modulo: Rest bei Division

[102]:
7%3
[102]:
1
[103]:
8%3
[103]:
2

Precedence rules

[104]:
1 + 2 * 3
[104]:
7
[105]:
(1 + 2) * 3
[105]:
9
[106]:
3 * 4 % 5
[106]:
2
[107]:
(3 * 4) % 5
[107]:
2
[108]:
3 * (4 % 5)
[108]:
12

Datatype Conversions

[109]:
i = 42
type(i)
[109]:
int
[110]:
s = '42'
type(s)
[110]:
str
[111]:
i == s
[111]:
False
[112]:
s
[112]:
'42'

Explicit Conversion:

[113]:
int(s)
[113]:
42
[114]:
str(666)
[114]:
'666'
[115]:
str([1,2])
[115]:
'[1, 2]'
[116]:
try:
    int('0xdeadbeef')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> invalid literal for int() with base 10: '0xdeadbeef'
[117]:
int('0xdeadbeef', 16)
[117]:
3735928559
[118]:
float('1.234')
[118]:
1.234
[119]:
try:
    float('1,234')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> could not convert string to float: '1,234'

Object Lifetime

[120]:
l1 = [1,2,3]
[121]:
l2 = l1
[122]:
id(l1)
[122]:
140299327492352
[123]:
id(l2)
[123]:
140299327492352
[124]:
del l1
[125]:
del l2
[126]:
l1 = [1,2,3]
def f(l2):
    print(l2)
f(l1)
[1, 2, 3]
[127]:
del l1

Boolean, Short Circuit Evaluation

[128]:
def func_false():
    print('func_false called')
    return False
def func_true():
    print('func_true called')
    return True
[129]:
func_true() and func_false()
func_true called
func_false called
[129]:
False
[130]:
func_true() and func_true()
func_true called
func_true called
[130]:
True
[131]:
func_false() and func_true()
func_false called
[131]:
False

More String Methods

[132]:
s1 = 'abc'
s2 = 'def'
[133]:
s1 + s2
[133]:
'abcdef'
[134]:
s1 += ' hallo'
s1
[134]:
'abc hallo'

Dictionary Preview

[135]:
d = {
    'm': 'Mr.',
    'f': 'Mrs.',
    'd': 'Prs.',
}
[136]:
'm' in d
[136]:
True
[137]:
'x' in d
[137]:
False
[138]:
'x' not in d
[138]:
True
[139]:
d['m']
[139]:
'Mr.'
[140]:
try:
    d['x']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 'x'
[141]:
d
[141]:
{'m': 'Mr.', 'f': 'Mrs.', 'd': 'Prs.'}
[142]:
for element in d:
    print(element)
m
f
d
[143]:
for key in d.keys():
    print(key)
m
f
d
[144]:
for value in d.values():
    print(value)
Mr.
Mrs.
Prs.
[145]:
for element in d.items():
    print(element)
('m', 'Mr.')
('f', 'Mrs.')
('d', 'Prs.')
[146]:
for element in d.items():
    key = element[0]
    value = element[1]
    print(key, value)
m Mr.
f Mrs.
d Prs.
[147]:
for key, value in d.items():
    print(key, value)
m Mr.
f Mrs.
d Prs.
[148]:
for element in [1,2,3]:
    print(element)
1
2
3

More String Methods

[149]:
s = 'abc:1:2:def'
[150]:
fields = s.split(':')
fields
[150]:
['abc', '1', '2', 'def']
[151]:
name, uid, gid, home = fields     # <--- tuple unpacking
[152]:
print('name:', name, ', uid:', uid, ', gid:', gid, ', home:', home)
name: abc , uid: 1 , gid: 2 , home: def
[153]:
print(f'name: {name}, uid: {uid}, gid: {gid}, home: {home}')
name: abc, uid: 1, gid: 2, home: def
[154]:
sex_options = ['m', 'f', 'd']
','.join(sex_options)
[154]:
'm,f,d'

Compound Datatypes

list: Mutable

[155]:
l = [1,2,'drei']
type(l)
[155]:
list
[156]:
id(l)
[156]:
140298898107648
[157]:
l.append(4)
[158]:
l
[158]:
[1, 2, 'drei', 4]
[159]:
id(l)
[159]:
140298898107648
[160]:
l.extend([5,'sechs',7.0])
[161]:
l
[161]:
[1, 2, 'drei', 4, 5, 'sechs', 7.0]
[162]:
id(l)
[162]:
140298898107648
[163]:
l += ['acht', 9]
l
[163]:
[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9]
[164]:
l1 = [10, 11]
new_l = l + l1
new_l
[164]:
[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9, 10, 11]
[165]:
l
[165]:
[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9]
[166]:
l1
[166]:
[10, 11]
[167]:
l * 3
[167]:
[1,
 2,
 'drei',
 4,
 5,
 'sechs',
 7.0,
 'acht',
 9,
 1,
 2,
 'drei',
 4,
 5,
 'sechs',
 7.0,
 'acht',
 9,
 1,
 2,
 'drei',
 4,
 5,
 'sechs',
 7.0,
 'acht',
 9]

list(): explicit constructor

[168]:
l = ['a', 'b', 'c']
l
[168]:
['a', 'b', 'c']
[169]:
s = 'abc'
[170]:
l = []
for element in s:
    l.append(element)
l
[170]:
['a', 'b', 'c']
[171]:
l = list(s)
l
[171]:
['a', 'b', 'c']
[172]:
d = {
    'm': 'Mr.',
    'f': 'Mrs.',
    'd': 'Prs.',
}
[173]:
l = list(d)
l
[173]:
['m', 'f', 'd']
[174]:
l = list(range(24))
l
[174]:
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23]
[175]:
23 in l
[175]:
True
[176]:
10**100 in l
[176]:
False

tuple: Immutable

[177]:
t = (1,2,'drei')
type(t)
[177]:
tuple
[178]:
try:
    t.append(4)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'
[179]:
t_mit_einem_element = (1)     # <--- operator precedence
print(t_mit_einem_element)
1
[180]:
if (True):
    print('eh')
eh
[181]:
type(t_mit_einem_element)
[181]:
int
[182]:
t_mit_einem_element = (1,)
print(t_mit_einem_element)
(1,)

dict: Mutable

[183]:
d = {1:'one', 2:'two'}
type(d)
[183]:
dict
[184]:
d[1]
[184]:
'one'
[185]:
1 in d
[185]:
True
[186]:
3 in d
[186]:
False
[187]:
3 not in d
[187]:
True
[188]:
d[3] = 'three'
[189]:
3 in d
[189]:
True
[190]:
d[3]
[190]:
'three'
[191]:
try:
    d[4]
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 4
[192]:
value = d.get(4)
if value is None:
    print('leider nicht')
else:
    print('supi:', value)
leider nicht
[193]:
del d[3]
[194]:
3 in d
[194]:
False

set: Mutable

[195]:
s = {1, 'zwei', 3.0}
[196]:
1 in s
[196]:
True
[197]:
'drei' not in s
[197]:
True
[198]:
'drei' in s
[198]:
False
[199]:
s.add(100)
[200]:
100 in s
[200]:
True
[201]:
s.remove(1)
[202]:
1 in s
[202]:
False
[203]:
try:
    s.remove(300)
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 300
[204]:
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7}
[205]:
s1 | s2
[205]:
{1, 2, 3, 4, 5, 6, 7}
[206]:
s1 - s2
[206]:
{1, 2, 3}
[207]:
s1 ^ s2
[207]:
{1, 2, 3, 6, 7}
[208]:
for element in s:
    print(element)
3.0
100
zwei
[209]:
for element in s:
    print(element)
3.0
100
zwei

Slicing

[210]:
l = [23, 45, 1, 8]
l[1:3]
[210]:
[45, 1]
[211]:
l[1:4]
[211]:
[45, 1, 8]
[212]:
l[1:]
[212]:
[45, 1, 8]

Comprehensions

List comprehension

[213]:
l = [3, 6, 1, 2]
squares = []
for element in l:
    squares.append(element**2)
squares
[213]:
[9, 36, 1, 4]
[214]:
def squares(nums):
    squares = []
    for element in nums:
        squares.append(element**2)
    return squares
squares(l)
[214]:
[9, 36, 1, 4]
[215]:
l
[215]:
[3, 6, 1, 2]
[216]:
[element**2 for element in l]
[216]:
[9, 36, 1, 4]

DIctionary Comprehension

[217]:
l
[217]:
[3, 6, 1, 2]
[218]:
squares_map = {}
for element in l:
    squares_map[element] = element**2
squares_map
[218]:
{3: 9, 6: 36, 1: 1, 2: 4}
[219]:
{element: element**2 for element in l}
[219]:
{3: 9, 6: 36, 1: 1, 2: 4}

Set Comprehension

[220]:
squares_set = set()
for element in l:
    squares_set.add(element**2)
squares_set
[220]:
{1, 4, 9, 36}
[221]:
{element**2 for element in l}
[221]:
{1, 4, 9, 36}

max

[222]:
max([2,3,1,5,3])
[222]:
5
[223]:
max(2,3,1,5,3)
[223]:
5

Generators

[224]:
r = range(3)
[225]:
for element in r:
    print(element)
0
1
2
[226]:
r = range(3)
type(r)
[226]:
range
[227]:
it = iter(r)
type(it)
[227]:
range_iterator
[228]:
next(it)
[228]:
0
[229]:
next(it)
[229]:
1
[230]:
next(it)
[230]:
2
[231]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>

while

[232]:
summe = 0
num = 1
while num <= 100:
    summe += num
    num += 1
print(summe)
5050
[233]:
summe = 0
for num in range(1, 101):
    summe += num
print(summe)
5050
[234]:
sum(range(1,101))
[234]:
5050
[235]:
import random

numtries = 0
won = False
while numtries < 6:
    numtries += 1
    eyes = random.randrange(1, 7)
    if eyes == 6:
        won = True
        break
if won:
    print('win')
else:
    print('lose')
win
[236]:
import random

numtries = 0
while numtries < 6:
    numtries += 1
    eyes = random.randrange(1, 7)
    if eyes == 6:
        print('win')
        break
else:
    print('lose')
lose

for, enumerate()

[237]:
l = ['Hallo', 'Joerg']
for element in l:
    print(element)
Hallo
Joerg
[238]:
l = ['Hallo', 'Joerg']
[print(element) for element in l]
Hallo
Joerg
[238]:
[None, None]
[239]:
l = ['Hallo', 'Joerg']
pos = 0
for element in l:
    print(pos, element)
    pos += 1
0 Hallo
1 Joerg
[240]:
l = ['Hallo', 'Joerg']
for element in enumerate(l):
    print(element)
(0, 'Hallo')
(1, 'Joerg')
[241]:
l = ['Hallo', 'Joerg']
for pos, element in enumerate(l):
    print(pos, element)
0 Hallo
1 Joerg

Functions

[246]:
def maximum(a, b):
    '''berechnet blah kompliziert blah maximum'''
    if a < b:
        return b
    else:
        return a
[247]:
type(maximum)
[247]:
function
[249]:
maximum.__doc__
[249]:
'berechnet blah kompliziert blah maximum'
[250]:
a = maximum
[251]:
a(2, 3)
[251]:
3
[253]:
maximum('abc', 'def')
[253]:
'def'
[255]:
try:
    maximum('1', 1)
except Exception as e:
    print(type(e), e)
<class 'TypeError'> '<' not supported between instances of 'str' and 'int'
[256]:
maximum(1, 1.5)
[256]:
1.5
[257]:
1 < 1.5
[257]:
True
[263]:
def greet(who, phrase='Guten Morgen'):
    print(phrase, who)
[265]:
greet('Joerg')
Guten Morgen Joerg
[269]:
greet('Joerg', phrase='Guten Morgen')
Guten Morgen Joerg

Iteratoren, Generatoren

[270]:
r = range(3)
type(r)
[270]:
range
[271]:
it = iter(r)
type(it)
[271]:
range_iterator
[272]:
next(it)
[272]:
0
[274]:
next(it)
[274]:
1
[275]:
next(it)
[275]:
2
[277]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[278]:
l = [3, 4]
it = iter(l)
next(it)
[278]:
3
[279]:
next(it)
[279]:
4
[281]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[283]:
for element in range(3):
    print(element)
0
1
2
[284]:
for element in l:
    print(element)
3
4

Generatoren

[287]:
def even_numbers(limit):
    numbers = []
    i = 0
    while i < limit:
        if i % 2 == 0:
            numbers.append(i)
        i += 1
    return numbers
[288]:
for element in even_numbers(10):
    print(element)
0
2
4
6
8
[289]:
def even_numbers(limit):
    i = 0
    while i < limit:
        if i % 2 == 0:
            yield i
        i += 1
[290]:
en = even_numbers(10)
type(en)
[290]:
generator
[291]:
it = iter(en)
type(it)
[291]:
generator
[292]:
next(it)
[292]:
0
[293]:
next(it)
[293]:
2
[294]:
next(it)
[294]:
4
[295]:
next(it)
[295]:
6
[296]:
next(it)
[296]:
8
[298]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>

Miscellaneous String Methods

[299]:
s = 'joerg'
[301]:
s.upper()
[301]:
'JOERG'
[302]:
s
[302]:
'joerg'
[303]:
s = s.upper()
s
[303]:
'JOERG'
[304]:
s.isupper()
[304]:
True
[305]:
s.isalnum()
[305]:
True
[307]:
s.isalpha()
[307]:
True
[309]:
s.isdigit()
[309]:
False
[310]:
s = 'mississppi'
s.count('ss')
[310]:
2
[312]:
s.find('ss')
[312]:
2
[313]:
pos = s.find('ss')
pos = s.find('ss', pos+1)
pos
[313]:
5
[314]:
s.find('xxx')
[314]:
-1
[315]:
if s.find('xxx'):
    print('jo')
else:
    print('na')
jo
[316]:
s.index('ss')
[316]:
2
[318]:
try:
    s.index('xxx')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> substring not found
[319]:
'hallo du'.startswith('hallo')
[319]:
True
[320]:
'file.csv'.endswith('.csv')
[320]:
True

split und join

[321]:
line = 'joerg:faschingbauer:1037190666'
fields = line.split(':')
fields
[321]:
['joerg', 'faschingbauer', '1037190666']
[322]:
firstname, lastname, svnr = line.split(':')
[323]:
firstname
[323]:
'joerg'
[324]:
fields
[324]:
['joerg', 'faschingbauer', '1037190666']
[325]:
','.join(fields)
[325]:
'joerg,faschingbauer,1037190666'

strip()

[326]:
s = '        xxx       '
s.strip()
[326]:
'xxx'
[327]:
s.rstrip()
[327]:
'        xxx'
[328]:
s.lstrip()
[328]:
'xxx       '
[329]:
s = ' a   \t       xxxx     \n a '
s.strip(' a\t\n')
[329]:
'xxxx'
[330]:
s.rstrip(' a\t\n')
[330]:
' a   \t       xxxx'

File I/O

[331]:
f = open('/etc/passwd')
[332]:
f = open('/etc/passwd', encoding='ascii')
[333]:
f.read()
[333]:
'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\nadm:x:3:4:adm:/var/adm:/sbin/nologin\nlp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:/sbin/nologin\noperator:x:11:0:operator:/root:/sbin/nologin\ngames:x:12:100:games:/usr/games:/sbin/nologin\nftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\nnobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\napache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\nsystemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\nsystemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\nsystemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\nsystemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\nsystemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\ntss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\ndbus:x:81:81:System message bus:/:/sbin/nologin\npolkitd:x:996:994:User for polkitd:/:/sbin/nologin\navahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\nunbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\ndnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\nnm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\nusbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\ngluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\nrtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\npipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\ngeoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\nchrony:x:989:984::/var/lib/chrony:/sbin/nologin\nsaslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\nradvd:x:75:75:radvd user:/:/sbin/nologin\nrpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\nqemu:x:107:107:qemu user:/:/sbin/nologin\nopenvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\nnm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\ncolord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\nrpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\nabrt:x:173:173::/etc/abrt:/sbin/nologin\nflatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\ngdm:x:42:42::/var/lib/gdm:/sbin/nologin\ngnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\nvboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\nsshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\ntcpdump:x:72:72::/:/sbin/nologin\njfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\nmosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\nsomeone-else:x:1001:1001::/home/someone-else:/bin/bash\n'
[334]:
f = open('/etc/passwd', encoding='ascii')
[335]:
f.read(15)
[335]:
'root:x:0:0:root'
[336]:
f = open('/etc/passwd', encoding='ascii')
[337]:
lines = f.readlines()
[339]:
lines
[339]:
['root:x:0:0:root:/root:/bin/bash\n',
 'bin:x:1:1:bin:/bin:/sbin/nologin\n',
 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',
 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',
 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',
 'sync:x:5:0:sync:/sbin:/bin/sync\n',
 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n',
 'halt:x:7:0:halt:/sbin:/sbin/halt\n',
 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n',
 'operator:x:11:0:operator:/root:/sbin/nologin\n',
 'games:x:12:100:games:/usr/games:/sbin/nologin\n',
 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n',
 'nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\n',
 'apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n',
 'systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n',
 'systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\n',
 'systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\n',
 'systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\n',
 'systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\n',
 'tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\n',
 'dbus:x:81:81:System message bus:/:/sbin/nologin\n',
 'polkitd:x:996:994:User for polkitd:/:/sbin/nologin\n',
 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n',
 'unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n',
 'dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\n',
 'nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\n',
 'usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n',
 'gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\n',
 'rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n',
 'pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\n',
 'geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\n',
 'chrony:x:989:984::/var/lib/chrony:/sbin/nologin\n',
 'saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n',
 'radvd:x:75:75:radvd user:/:/sbin/nologin\n',
 'rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n',
 'qemu:x:107:107:qemu user:/:/sbin/nologin\n',
 'openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\n',
 'nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\n',
 'colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\n',
 'rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n',
 'abrt:x:173:173::/etc/abrt:/sbin/nologin\n',
 'flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\n',
 'gdm:x:42:42::/var/lib/gdm:/sbin/nologin\n',
 'gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\n',
 'vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\n',
 'sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\n',
 'tcpdump:x:72:72::/:/sbin/nologin\n',
 'jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\n',
 'mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n',
 'someone-else:x:1001:1001::/home/someone-else:/bin/bash\n']
[340]:
for line in lines:
    print(line)
root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin

apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin

systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin

systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin

systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin

systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin

tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin

dbus:x:81:81:System message bus:/:/sbin/nologin

polkitd:x:996:994:User for polkitd:/:/sbin/nologin

avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin

unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin

dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin

usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin

gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin

rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin

pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin

geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin

chrony:x:989:984::/var/lib/chrony:/sbin/nologin

saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin

radvd:x:75:75:radvd user:/:/sbin/nologin

rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin

qemu:x:107:107:qemu user:/:/sbin/nologin

openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin

nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin

colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin

rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin

abrt:x:173:173::/etc/abrt:/sbin/nologin

flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin

gdm:x:42:42::/var/lib/gdm:/sbin/nologin

gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin

vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin

sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin

tcpdump:x:72:72::/:/sbin/nologin

jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash

mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin

someone-else:x:1001:1001::/home/someone-else:/bin/bash

[341]:
f = open('/etc/passwd', encoding='ascii')
[342]:
for line in f:
    print(line)
root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin

apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin

systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin

systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin

systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin

systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin

tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin

dbus:x:81:81:System message bus:/:/sbin/nologin

polkitd:x:996:994:User for polkitd:/:/sbin/nologin

avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin

unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin

dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin

usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin

gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin

rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin

pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin

geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin

chrony:x:989:984::/var/lib/chrony:/sbin/nologin

saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin

radvd:x:75:75:radvd user:/:/sbin/nologin

rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin

qemu:x:107:107:qemu user:/:/sbin/nologin

openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin

nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin

colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin

rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin

abrt:x:173:173::/etc/abrt:/sbin/nologin

flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin

gdm:x:42:42::/var/lib/gdm:/sbin/nologin

gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin

vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin

sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin

tcpdump:x:72:72::/:/sbin/nologin

jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash

mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin

someone-else:x:1001:1001::/home/someone-else:/bin/bash

dict vs. OrderedDict

[343]:
d = {}
[344]:
d['five'] = 5
[345]:
d['three'] = 3
[346]:
for k in d.keys():
    print(k)
five
three
[348]:
import collections

od = collections.OrderedDict(d.items())
od
[348]:
OrderedDict([('five', 5), ('three', 3)])
[349]:
od['five']
[349]:
5
[351]:
found = od.get('ten')
print(found)
None
[352]:
for k in od.keys():
    print(k)
five
three
[353]:
od.move_to_end('five')
[354]:
for k in od.keys():
    print(k)
three
five

Object Oriented Programming

Duck Typing

[1]:
class ThermometerA:
    def __init__(self, t):
        self.temp = t
    def get_temperature(self):
        return self.temp
[3]:
class ThermometerB:
    def __init__(self, t):
        self.temp = t
    def get_temperature(self):
        return self.temp
[4]:
a = ThermometerA(10)
a.get_temperature()
[4]:
10
[6]:
b = ThermometerB(20)
b.get_temperature()
[6]:
20
[7]:
def get_average_temperature(th_list):
    avg = 0
    for t in th_list:
        avg += t.get_temperature()
    return avg/len(th_list)
[8]:
get_average_temperature([a, b])
[8]:
15.0

Interfaces

[23]:
class Thermometer:
    def get_temperature(self):
        assert False, 'this must be implemented'
[24]:
class ThermometerA(Thermometer):
    def __init__(self, t):
        self.temp = t
    def get_temperature(self):
        return self.temp
[25]:
class ThermometerB:
    def __init__(self, t):
        self.temp = t
    def get_temperature(self):
        return self.temp
[26]:
a = ThermometerA(10)
a.get_temperature()
[26]:
10
[28]:
b = ThermometerB(100)
b.get_temperature()
[28]:
100
[31]:
def get_average_temperature(th_list):
    avg = 0
    for t in th_list:
        if not isinstance(t, Thermometer):
            raise TypeError(f'{t} is not a Thermometer')
        avg += t.get_temperature()
    return avg/len(th_list)
[32]:
get_average_temperature([a,b])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_9164/859664274.py in <module>
----> 1 get_average_temperature([a,b])

/tmp/ipykernel_9164/2942790015.py in get_average_temperature(th_list)
      3     for t in th_list:
      4         if not isinstance(t, Thermometer):
----> 5             raise TypeError(f'{t} is not a Thermometer')
      6         avg += t.get_temperature()
      7     return avg/len(th_list)

TypeError: <__main__.ThermometerB object at 0x7fac83797be0> is not a Thermometer
[34]:
issubclass(ThermometerA, Thermometer)
[34]:
True
[35]:
issubclass(ThermometerB, Thermometer)
[35]:
False
[36]:
class ThermometerB(Thermometer):
    def __init__(self, t):
        self.temp = t
    def get_temperature(self):
        return self.temp
[38]:
b = ThermometerB(1000)
[39]:
get_average_temperature([a, b])
[39]:
505.0

Implementation Inheritance

[23]:
class Thermometer:
    def get_temperature(self):
        assert False, 'this must be implemented'
[42]:
class ThermometerA(Thermometer):
    def __init__(self, name, t):
        self.name = name
        self.temp = t
    def get_temperature(self):
        return self.temp
[41]:
class ThermometerB(Thermometer):
    def __init__(self, name, t):
        self.name = name
        self.temp = t
    def get_temperature(self):
        return self.temp
[45]:
a = ThermometerA(name='Ein A Thermometer', t=10)
a.name
[45]:
'Ein A Thermometer'
[47]:
b = ThermometerB(name='Ein B Thermometer', t=1000)
b.name
[47]:
'Ein B Thermometer'

Nun aber fassen wir name in die Basisklasse

[51]:
class Thermometer:
    def __init__(self, name):
        self.name = name
    def get_temperature(self):
        assert False, 'this must be implemented'
[59]:
class ThermometerA(Thermometer):
    def __init__(self, name, t):
        super().__init__(name)
        self.temp = t
    def get_temperature(self):
        return self.temp
[63]:
class ThermometerB(Thermometer):
    def __init__(self, name, t):
        super().__init__(name)
        self.temp = t
    def get_temperature(self):
        return self.temp
[60]:
a = ThermometerA(name='Joerg', t=10)
[61]:
a.__dict__
[61]:
{'name': 'Joerg', 'temp': 10}
[64]:
a.name
[64]:
'Joerg'
[65]:
b = ThermometerB('Hansi', 100)
b.name
[65]:
'Hansi'

Method Resolution Order (MRO), and super()

[66]:
class Base:
    def f(self):
        print('Base.f')
[72]:
class Level2_1(Base):
    def f(self):
        print('Level2_1.f')
        super().f()
[74]:
l21 = Level2_1()
l21.f()
Level2_1.f
Base.f
[75]:
class Level2_2(Base):
    def f(self):
        print('level2_2.f')
        super().f()
[78]:
class Level3(Level2_1, Level2_2):
    def f(self):
        print('Level3.f')
        super().f()
[79]:
l3 = Level3()
l3.f()
Level3.f
Level2_1.f
level2_2.f
Base.f

__bases__

[80]:
Base.__bases__
[80]:
(object,)
[81]:
Level2_1.__bases__
[81]:
(__main__.Base,)
[83]:
Level2_2.__bases__
[83]:
(__main__.Base,)
[85]:
Level3.__bases__
[85]:
(__main__.Level2_1, __main__.Level2_2)

__mro__

[86]:
Level3.__mro__
[86]:
(__main__.Level3, __main__.Level2_1, __main__.Level2_2, __main__.Base, object)
[87]:
Level2_1.__mro__
[87]:
(__main__.Level2_1, __main__.Base, object)
[88]:
Base.__mro__
[88]:
(__main__.Base, object)

Object Layout (self)

[89]:
class Jedi:
    def f(self):
        self.force = 15
[94]:
class Luke(Jedi):
    def f(self):
        self.blueeyes = True
        super().f()
[97]:
luke = Luke()
luke.__dict__
[97]:
{}
[96]:
luke.f()
luke.__dict__
[96]:
{'blueeyes': True, 'force': 15}

More from OO

[111]:
class Robot:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return 'Robot name is: ' + self.name
[112]:
class Droid(Robot):
    def __str__(self):
        return 'Droid name is: ' + self.name
[114]:
d = Droid('R2D2')
[117]:
d.name
[117]:
'R2D2'
[119]:
print(d)
Droid name is: R2D2
[120]:
d.__str__()
[120]:
'Droid name is: R2D2'
[121]:
d.__dict__
[121]:
{'name': 'R2D2'}
[122]:
d.__dict__['name']
[122]:
'R2D2'
[123]:
d.name
[123]:
'R2D2'
[124]:
type(Droid)
[124]:
type
[125]:
Droid.__dict__
[125]:
mappingproxy({'__module__': '__main__',
              '__str__': <function __main__.Droid.__str__(self)>,
              '__doc__': None})
[126]:
Droid.__bases__
[126]:
(__main__.Robot,)
[127]:
Droid.__bases__[0].__dict__
[127]:
mappingproxy({'__module__': '__main__',
              '__init__': <function __main__.Robot.__init__(self, name)>,
              '__str__': <function __main__.Robot.__str__(self)>,
              '__dict__': <attribute '__dict__' of 'Robot' objects>,
              '__weakref__': <attribute '__weakref__' of 'Robot' objects>,
              '__doc__': None})

Operator Overloading

[155]:
class Integer:
    def __init__(self, value):
        print('__init__')
        self.value = value
    def __str__(self):
        print('__str__')
        return str(self.value)
    def __lt__(self, rhs):
        if self.value < rhs.value:
            return True
        else:
            return False
    def __add__(self, rhs):
        return Integer(self.value + rhs.value)
[149]:
i = Integer(42)
print(i)
__init__
__str__
42
[150]:
j = Integer(666)
__init__
[152]:
i < j
[152]:
True
[156]:
s = i + j
print(s)
__init__
__str__
708

Calling Base Class Constructor (Many Ways)

[173]:
class Base:
    def __init__(self, val):
        print('Base.__init__')
        self.val = val
[174]:
class DerivedNoCtor(Base):
    pass
[175]:
dnoctor = DerivedNoCtor(10)
Base.__init__
[176]:
dnoctor.val
[176]:
10
[181]:
class DerivedCtorCallingSuper(Base):
    def __init__(self, val):
        print('DerivedCtorCallingSuper.__init__')
        super().__init__(val)
[180]:
o = DerivedCtorCallingSuper(666)
DerivedCtorCallingSuper.__init__
Base.__init__
[183]:
class DerivedCtorCallingBaseCtor(Base):
    def __init__(self, val):
        print('DerivedCtorCallingBaseCtor.__init__')
        Base.__init__(self, val)
[184]:
o = DerivedCtorCallingBaseCtor(42)
DerivedCtorCallingBaseCtor.__init__
Base.__init__

Name Mangling (“private” Members)

[185]:
class User:
    def __init__(self, firstname, lastname):
        self.__firstname = firstname
        self.__lastname = lastname
[188]:
try:
    u.__firstname
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'User' object has no attribute '__firstname'
[186]:
u = User("Joerg", "Faschingbauer")
u.__dict__
[186]:
{'_User__firstname': 'Joerg', '_User__lastname': 'Faschingbauer'}
[189]:
u._User__firstname
[189]:
'Joerg'

Properties

[200]:
class User:
    def __init__(self, firstname, lastname):
        self.__firstname = firstname
        self.__lastname = lastname
    @property
    def firstname(self):
        return self.__firstname

    @property
    def lastname(self):
        return self.__lastname

    @property
    def name(self):
        return self.__firstname + ' ' + self.__lastname
[201]:
u = User("Joerg", "Faschingbauer")
u.name
[201]:
'Joerg Faschingbauer'
[202]:
u.firstname
[202]:
'Joerg'
[204]:
u.lastname
[204]:
'Faschingbauer'
[206]:
try:
    u.lastname = 'Huber'
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> can't set attribute

Yet Another Example From Udemy

[286]:
class Jedi:
    LightSaber = True
[287]:
class Padawan(Jedi):
    def __init__(self, name):
        self.name = name
[288]:
issubclass(Padawan, Jedi)
[288]:
True
[289]:
p = Padawan('Joerg')
[290]:
isinstance(p, Padawan)
[290]:
True
[291]:
isinstance(p, Jedi)
[291]:
True
[292]:
p.name
[292]:
'Joerg'
[293]:
hasattr(p, 'name')
[293]:
True
[294]:
getattr(p, 'name')
[294]:
'Joerg'
[295]:
p.__dict__.get('name')
[295]:
'Joerg'
[297]:
hasattr(Jedi, 'LightSaber')
[297]:
True
[299]:
hasattr(Padawan, 'LightSaber')
[299]:
True
[300]:
Padawan.LightSaber
[300]:
True

Exception Handling

Order of except Clauses

[159]:
try:
    1/0
except ArithmeticError:
    print('ArithmeticError')
except ZeroDivisionError:
    print('ZeroDivisionError')
ArithmeticError
[160]:
issubclass(ZeroDivisionError, ArithmeticError)
[160]:
True
[161]:
try:
    1/0
except ZeroDivisionError:
    print('ZeroDivisionError')
except ArithmeticError:
    print('ArithmeticError')
ZeroDivisionError

else

[162]:
try:
    print('hallo du suesser!')
except OSError as e:
    print('WAAAH hardware abgebrannt!', e)
else:
    print('puh, hardware intakt')
hallo du suesser!
puh, hardware intakt

finally

[169]:
try:
    print('hallo du suesser!')
except OSError as e:
    print('WAAAH hardware abgebrannt!', e)
else:
    print('puh, hardware intakt')   # only if no exception
finally:
    print('wurscht, vorbei is')    # in any case
hallo du suesser!
puh, hardware intakt
wurscht, vorbei is

lambda

[213]:
def f(x):
    if x > 1:
        return 1
    else:
        return 0

[208]:
f(3)
[208]:
1
[209]:
f(1)
[209]:
0
[214]:
f = lambda x: 1 if x>1 else 0
[212]:
f(1)
[212]:
0

map(), filter()

[215]:
def square(num):
    return num**2
[216]:
l = [2, 1, 5, 3, 6]
for element in map(square, l):
    print(element)
4
1
25
9
36
[217]:
m = map(square, l)
type(m)
[217]:
map
[218]:
for element in map(lambda num: num**2, l):
    print(element)
4
1
25
9
36
[219]:
l
[219]:
[2, 1, 5, 3, 6]
[222]:
def is_even(num):
    if num%2 == 0:
        return True
    return False
[223]:
for element in filter(is_even, l):
    print(element)
2
6

Generators, Iteration Protocol

[224]:
r = range(3)
[226]:
for element in r:
    print(element)
0
1
2
[227]:
r = range(3)
[228]:
it = iter(r)
[229]:
next(it)
[229]:
0
[230]:
next(it)
[230]:
1
[231]:
next(it)
[231]:
2
[233]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[234]:
def my_range(limit):
    i = 0
    while i < limit:
        yield i
        i += 1
[235]:
for element in my_range(3):
    print(element)
0
1
2
[236]:
r = my_range(3)
[238]:
type(r)
[238]:
generator
[241]:
it = iter(r)
[242]:
next(it)
[242]:
0
[243]:
next(it)
[243]:
1
[244]:
next(it)
[244]:
2
[246]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>

Class Variables (as Opposed to Instance Variables)

[257]:
class Blah:
    instances = []

    def __init__(self, value):
        Blah.instances.append(self)
        self.value = value
[258]:
Blah.instances
[258]:
[]
[259]:
b = Blah(42)
[260]:
b.instances
[260]:
[<__main__.Blah at 0x7fac81f52df0>]
[261]:
b.value
[261]:
42
[262]:
c = Blah(23)
[263]:
Blah.instances
[263]:
[<__main__.Blah at 0x7fac81f52df0>, <__main__.Blah at 0x7fac81cb5700>]
[253]:
Blah.__init__
[253]:
<function __main__.Blah.__init__(self, value)>

Raw Strings

[264]:
s = 'C:\Progamme\noch ein programm\tumpfbacke'
[265]:
print(s)
C:\Progamme
och ein programm        umpfbacke
[266]:
s = 'C:\\Progamme\\noch ein programm\\tumpfbacke'
[267]:
print(s)
C:\Progamme\noch ein programm\tumpfbacke
[268]:
s = r'C:\Progamme\noch ein programm\tumpfbacke'
[269]:
print(s)
C:\Progamme\noch ein programm\tumpfbacke

File IO

[270]:
f = open('file.txt', 'rt')  # r and t are default anyway
[271]:
for line in f:
    print(line)
zeile 1

zeile 2

zeile 3

zeile 4

[273]:
f = open('file.txt', 'rt')  # r and t are default anyway
[274]:
for line in f:
    print(line, end='')
zeile 1
zeile 2
zeile 3
zeile 4
[278]:
f = open('file.txt', 'rt')  # r and t are default anyway
[279]:
wholefile = f.read()
wholefile
[279]:
'zeile 1\nzeile 2\nzeile 3\nzeile 4\n'
[280]:
print(wholefile)
zeile 1
zeile 2
zeile 3
zeile 4

[281]:
f = open('file.txt', 'rt')  # r and t are default anyway
[282]:
wholefile = f.read()
for c in wholefile:
    print(c)
z
e
i
l
e

1


z
e
i
l
e

2


z
e
i
l
e

3


z
e
i
l
e

4


[284]:
f = open('file.txt', 'rt')  # r and t are default anyway
[285]:
wholefile = f.read()
for c in wholefile:
    print(c, end='')
zeile 1
zeile 2
zeile 3
zeile 4