Short Python Tricks

print

>>> print(10, 20, 30, sep=": ")
10: 20: 30

print center

>>> print(f" First tip of the day ".center(50, '-')
-------- First tip of the day --------

initialize a set

>>> set_1 = {""}
>>> print(type(set_1))
<class 'set'>
>>> print(set_1)
{''}

>>> set_2 = {*""}
>>> print(type(set_2))
<class 'set'>
>>> print(set_2)
set()

## for a dictionary
>>> dic_1 ={}
>>> print(type(dic_1))
<class 'dict'>
>>> print(dic_1)
{}

__call__()

def add1(x, y):
   return x + y

class Adder:
   def __call__(self, x, y):
      return x + y
add2 = Adder()

>>> add1(10, 20)
30

>>> add2(10, 20)
30

Set default values to NamedTuple

>>> from collections import namedtuple
>>> Task = namedtuple('Task', ['summary', 'owner', 'done', 'id'])
>>> Task.__new__.__defaults__ = (None, 'Me', False, 0)

Get time statistics when running algorithm

import time
import numpy as np

def do_this():
    time.sleep(0.5)

result = %timeit -n5 -o do_this()
result = np.asarray(result.all_runs)
print('{:.1f} +- {:.1f}'.format(result.mean(), result.std()))
$ 501 ms ± 27.1 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
$ 2.5 +- 0.0

More about this in the python documentation of timeit

Modulo (%)

Modulo is easy to understand, right?

>>> 11 % 5
1

Well of course because 5 * 2 + 1 = 11

So what about this one, did you expect that

>>> -11 % 5
4

Well this is because (-3) * 5 + 4 = -11