User Tools

Site Tools


python_notes

dummy

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
importlib.util.find_spec("foo")

Alternative:

import imp
imp.find_module("foo")

Note:

  • 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:
    logger.info('Input file is empty.')
    logger.info('Writing an empty output file.')
    with open(output_file, 'w') as fp:
        pass

config files

python mailing list

python reference

python tutorials

python release cycle

tasks

isinstance experiments

In [1]: 
isinstance(True, int)
Out[1]: 
True

In [2]: 
type(True) is int
Out[2]: 
False

Using Python 3.9.5

Snippets

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

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

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

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
sleep(10)

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

assert variable in a list

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

$ python junk51.py
Traceback (most recent call last):
  File "C:\Users\kkusuman\x\junk51.py", 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

dummy

python_notes.txt · Last modified: 2022/03/08 18:47 by raju