Skip to content

Instantly share code, notes, and snippets.

@saveshodhan
Last active April 17, 2021 08:51
Show Gist options
  • Save saveshodhan/28a9b2e222629a21cbd1d9f8fce4cb23 to your computer and use it in GitHub Desktop.
Save saveshodhan/28a9b2e222629a21cbd1d9f8fce4cb23 to your computer and use it in GitHub Desktop.
Python snippets
  • Implementing pause
import os
os.system('read -s -n 1 -p "Press any key to continue...\n"')

  • Natural (human) sort (REF.)
    convert = lambda text: int(text) if text.isdigit() else text
    foo = ["f" + str(x) for x in range(20)]
    foo.sort()
    print foo   # ['f0', 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9']
    foo.sort(key=lambda x : [convert(c) for c in re.split('(\d+)', x)])
    print foo   # ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19']

  • Unicode to ASCII At times when we have certain unicode characters that Python is not able to convert to ASCII, it throws this exception:

    UnicodeEncodeError: 'ascii' codec can't encode character u'\uXXXX' in position 8: ordinal not in range(128)

    Where XXXX is some unicode value For e.g., if we have a unicode char 'en dash' (&#x2013) instead of the hyphen (&#x2d) (REF) for Unicode dash chars, the unicode value for en dash is U+2013 and for hyphen is U+002D

    >>> hyphen = u'\u002d'
    >>> en_dash = u'\u2013'
    >>> 
    >>> print hyphen
    -
    >>> print en_dash>>> print str(hyphen)
    -
    >>> print str(en_dash)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 0: ordinal not in range(128)

    To overcome this, we have a lib - unidecode:

    >>> import unidecode
    >>> unidecode.unidecode_expect_ascii(en_dash)
    '-'
    >>>
    

  • Nicely print Exceptions (more readings here and here)
    import linecache
    import sys
    
    def PrintException():
      exc_type, exc_obj, tb = sys.exc_info()
      f = tb.tb_frame
      lineno = tb.tb_lineno
      filename = f.f_code.co_filename
      linecache.checkcache(filename)
      line = linecache.getline(filename, lineno, f.f_globals)
      print '{} IN ({}, LINE {} "{}"): {}'.format(exc_type.__name__, filename, lineno, line.strip(), exc_obj)
      
    try:
      print 1/0
    except:
      PrintException()
    
    # Output:
    # ZeroDivisionError IN (foo.py, LINE 14 "print 1/0"): integer division or modulo by zero

Python 3

import sys
import traceback

def PrintException():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    formatted_exception = traceback.format_exception(
        etype=exc_type,
        value=exc_value,
        tb=exc_traceback
    )
    return "".join(formatted_exception)

  • dict of dict of stuff (without getting a KeyError) (REF.)
    >>> from collections import defaultdict
    >>>
    >>> d1 = defaultdict(lambda: 0)
    >>> d2 = defaultdict(list)
    >>> d3 = defaultdict(lambda: defaultdict(list))
    >>> 
    >>> print d1[1]
    0
    >>> d1
    defaultdict(<function <lambda> at 0x6f9c73b18de8>, {1: 0})
    >>> 
    >>> d2['1'].append(1)
    >>> d2
    defaultdict(<type 'list'>, {'1': [1]})
    >>> 
    >>> d3['1']['2'].append(12)
    >>> d3
    defaultdict(<function <lambda> at 0x6f9c73ab27d0>, {'1': defaultdict(<type 'list'>, {'2': [12]})})
    But never forget: Errors should never pass silently.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment