User Tools

Site Tools



validate inputs

Sample snippet:

day = 'foo'
valid_days = ['sun', 'mon', 'tue']
assert day in valid_days, '{} is not a valid day. '\
                          'It should be one of {}'.format(day, valid_days)

Sample output:

AssertionError                            Traceback (most recent call last)
<ipython-input-4-70d26d6f2c6d> in <module>
----> 1 assert day in valid_days, '{} is not a valid day. '\
      2                           'It should be one of {}'.format(day, valid_days)

AssertionError: foo is not a valid day. It should be one of ['sun', 'mon', 'tue']

where is a module imported from

tags | module path

one way:

import importlib.util


import imp


  • The imp module is deprecated in favour of importlib. So use the first approach whenever possible.

get the function name

empty file

Task: If input file is empty, write an empty output file

import os
if os.stat(input_file).st_size == 0:'Input file is empty.')'Writing an empty output file.')
    with open(output_file, 'w') as fp:

config files

python mailing list

python reference

python tutorials

python release cycle

isinstance experiments

In [1]: 
isinstance(True, int)

In [2]: 
type(True) is int

Using Python 3.9.5

write an extra line to file

with open('filename.txt', 'w') as fh:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.


See also:-


difference between


import from another project

Say we have two projects cloned into two directories - github/project1 and github/project2. To import stuff from project1 into a file in project2

import os
import sys

# Note: os.path.dirname(__file__) can give an empty string,
# use os.path.dirname(os.path.abspath(__file__)) instead.
# Ref:- See Dmitry Trofimov's comment in
dirname = os.path.dirname(os.path.abspath(__file__))

# Change the relative path as per your needs
newdir = os.path.abspath(os.path.join(dirname, '../project1'))

if newdir not in sys.path:
    sys.path.insert(0, newdir)

tags | import from many levels up, import from another directory, relative directory name, path relative to current file

check for minimum python version

import sys
if sys.version_info[:2] < (3, 7):
    raise RuntimeError('Requires Python 3.7 or greater')
from traceback import format_exc

    # my code
except Exception as exc:
    print 'caught exception while doing foo'
    print format_exc()
    print exc
from traceback import format_exc

    # my code
except Exception as exc:
    logger.error('Caught exception while doing stuff.')

When the code is executed in pycharm and the exception is encountered, the traceback is printed in both pycharm window and in the file.

To test the above code, you can raise a simple exception using

raise ValueError("test exception handling.")

sleep for 10 seconds

tags | sleep for N seconds

from time import sleep

Ref:- - well written article that talks about how you might use the sleep function in real life. Worth reading end-to-end once.

get the home directory

write file relative to home directory

import os
home = os.path.expanduser("~")
path = os.path.join(home, "x", "data.txt")

round function

The expression round(n, r) rounds floating-point expression $n$ to the $10^{-r}$ decimal digit; for example, round(n, -2) rounds floating-point value $n$ to the hundreds place $(10^2)$. Similarly, round(n, 3) rounds floating-point value n to the thousandths place $(10^{-3})$.

assert variable in a list

$ cat
letters = ["a", "b", "c"]
x = "1"
assert x in letters, "{} is not a valid letter. It should be one of {}".format(
    x, letters

$ python
Traceback (most recent call last):
  File "C:\Users\kkusuman\x\", line 3, in <module>
    assert x in letters, "{} is not a valid letter. It should be one of {}".format(
AssertionError: 1 is not a valid letter. It should be one of ['a', 'b', 'c']

memory consumed by a function

call different functions based on variable



came across


python_notes.txt · Last modified: 2023/02/15 22:10 by raju