Python

OOP

Call parent constuctor

super().__init__()

String formatting

  • using the % operator (old)
logger.debug('Got argument %s.' % arg)
  • str.format (new: string formatters)
print("Sammy has {} balloons.".format(5))
print("Sammy has {} and {} balloons.".format(5, 7))
print("Sammy has {0} and {1} balloons.".format(5, 7))
print("Sammy has {1} and {0} balloons.".format(5, 7))
  • interpolated strings
print("{firstname} {lastname}".format(firstname="Horst", lastname="Gutmann"))
  • new f-strings in Python 3.6
name = 'Fred'
age = 42
print(f'He said his name is {name} and he is {age} years old.')

logger

Logger is optimized to defer avaluation of arguments until it is needed, so for best performance use % formating. Instead of this:

logger.error('oops caused by %s' % exc)

do that:

logger.error('oops caused by %s', exc)

Exceptions

Ignore exception

try:
    do_something()
except Exception:
    pass