Python

Main page for all things Python. Other pages cover specific topics, such as:

Boolean unravelling

and

unravelling the and boolean operator. The operation can be rewritten as the function u_and:

def u_and(a, b):
  result = a
  if a:
    result = b
  return result

For instance:

a = True ; b = None
print(a and b, u_and(a, b))
a = True ; b = True
print(a and b, u_and(a, b))
a = False ; b = True
print(a and b, u_and(a, b))
None None
True True
False False

or

On the other hand, or cand be unravelled as:

def u_or(a, b):
  result = a
  if not a:
    result = b
  return result

As an example:

a = True ; b = None
print(a or b, u_or(a, b))
a = True ; b = True
print(a or b, u_or(a, b))
a = False ; b = True
print(a or b, u_or(a, b))
True True
True True
True True

The many faces of print

Concatenating arguments

var1 = "Foo"
var2 = "Bar"
print("I am ", var1, " not ", var2)
I am  Foo  not  Bar
var1 = "Foo"
var2 = "Bar"
print("I am ", var1, " not ", var2)
I am  Foo  not  Bar

It is also possible to use separators by using the sep argument:

var1 = "Foo"
var2 = "Bar"
print("I am", var1, "not", var2, sep="!")
I am!Foo!not!Bar

String termination

The end argument allows to specify the suffix of the whole string.

print("This is on radio", end=" (over)")
This is on radio (over)

Filesystem operations

Get home directory

For Python +3.5:

from pathlib import Path

home = str(Path.home())

List files recursively

For Python +3.5, use glob:

import glob

# root_dir with trailing slash (i.e. /root/dir/)
root_dir = "./tmp"
for filename in glob.iglob(root_dir + '**/*.md', recursive=True):
     print(filename)

Collections

Sort an object list by attribute

Assuming a list a with instances of Foo, such that

import random
from dataclasses import dataclass

@dataclass
class Foo:
    bar: str
    baz: int

a = [Foo(bar=f"foo-{i}", baz=random.randint(0, 100)) for i in range(50)]
a[1:5]
[Foo(bar='foo-1', baz=3),
 Foo(bar='foo-2', baz=30),
 Foo(bar='foo-3', baz=56),
 Foo(bar='foo-4', baz=34)]

To return a new collection:

a_sorted = sorted(a, key=lambda x: x.baz, reverse=False)
a_sorted[1:5]
[Foo(bar='foo-1', baz=3),
 Foo(bar='foo-28', baz=3),
 Foo(bar='foo-41', baz=5),
 Foo(bar='foo-15', baz=6)]

To sort in place using attribute bar:

a.sort(key=lambda x: x.baz, reverse=True)
a[1:5]
[Foo(bar='foo-40', baz=91),
 Foo(bar='foo-18', baz=87),
 Foo(bar='foo-37', baz=86),
 Foo(bar='foo-43', baz=86)]