Skip to content

Instantly share code, notes, and snippets.

Last active May 2, 2023 18:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Useful python

Clear tqdm error


Extend namedtuple with methods

ExperimentProps = namedtuple( 'ExperimentProps', config.keys() )
class Experiment(ExperimentProps):
    def root_path(self):
        return self._root_path

    def root_path(self, _val):
        if os.path.exists(_val):
            self._root_path = _val

    def network_path(self):
        return os.path.join( self._root_path, 'network',

    def get_skeleton(self):
        Load the skeleton, and return dict
        with open(self.skeleton, 'r') as f:
            skel = yaml.load(f, Loader=yaml.FullLoader)
        return skel
result = Experiment( *config.values() )

Simple struct

result = SimpleNamespace()
result.sizes = [ int(l[3]) for l in buf ] 
result.types = [ l[5] for l in buf ] 
result.names = [ l[6] for l in buf ] 

First item in generator

it = next(x for x in loader) item = next(iter(themap.keys()))

Interrupt tqdm

    with tqdm(...) as t:
        for i in t:
except KeyboardInterrupt:

Merge PDF files

import PyPDF2
tomerge = [ v for v in os.listdir('.') if 'pdf' in v ]

merger = PyPDF2.PdfFileMerger()
for f in tomerge:
    merger.append(PyPDF2.PdfFileReader( open(f, 'rb') ) )

Flatten 2-level list

from functools import reduce
l = [['a', 'b', 'c'], ['d'], ['e', 'f']]
reduce( lambda x,y: x+y, l )

List DLLs loaded by a process

From: StackOverflow

import psutil, os
p = psutil.Process( os.getpid() )  # current proc
for dll in p.memory_maps():

Disassemble expression

>>> import dis
>>> dis.dis("not x is None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>> dis.dis("x is not None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

Dynamic enums

actstr = 'stand,walk,run,sit'
Actions = Enum('Actions', { v:i for i,v in enumerate(actstr.split(',')) })
Actions['run'] # string name # index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment