Python

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

Language changes

Modules

Relative import in Python 3

If a relative import is present inside a Python 3 file (e.g. file1) inside a module (e.g. mymod), say

from .foo import bar

We will encounter the error

ImportError: attempted relative import with no known parent package

A possible solution is to include the following in your module's __init__.py:

import os, sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

Ternary operator

Ternary operators help reduce the amount of very small if-else blocks. Python does not have a ternary operator like other languages. However, conditionals can be used to the same effect:

y = 7
x = 0 if (y == 1) else 1
print(x)
1

for ... else

for-else blocks allow to capture if a condition was met inside a for-loop. For instance, consider the following for-loop:

locations = ['a', 'b', 'c', 'd', 'f']
treasure = False
for location in locations:
    if location == 'x':
        treasure = True
        break
if not treasure:
    print("X marks the spot, but not found")
X marks the spot, but not found

We can simplify the above logic using a for-else loop:

for location in locations:
    if location == 'x':
        break
else:
    print("X marks the spot, but not found")
X marks the spot, but not found

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


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


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


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


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


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)

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)