Skip to content

Instantly share code, notes, and snippets.

@co89757
Last active November 27, 2018 04:22
Show Gist options
  • Save co89757/6043884ed8b2d8546563 to your computer and use it in GitHub Desktop.
Save co89757/6043884ed8b2d8546563 to your computer and use it in GitHub Desktop.
code snippets and cookbook for py

String/ Text

Filter a string for a set of chars

import string
# Make a reusable string of all characters, which does double duty
# as a translation table specifying "no translation whatsoever"
allchars = string.maketrans('', '')
def makefilter(keep):
""" Return a function that takes a string and returns a partial copy
of that string consisting of only the characters in 'keep'.
Note that `keep' must be a plain string.
"""
# Make a string of all characters that are not in 'keep': the "set
# complement" of keep, meaning the string of characters we must delete
 delchars = allchars.translate(allchars, keep)
# Make and return the desired filtering function (as a closure)
 def thefilter(s):
  return s.translate(allchars, delchars)
  return thefilter

Python Modules

itertools

GOT-CHAs

Namespace and Scope

If a name is declared global, then all references and assignments go directly to the middle scope containing the module’s global names. Otherwise, all variables found outside of the innermost scope are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).

Decorators

Python decorators well explained

a logger decorator example

from functools import wraps
import time 

class logger(object):
    """logger decorator for functions recording:
    func name 
    args
    return value
    exec time
    """
    def __init__(self, fn):
        self.fn = fn 

    def __call__(self, *args, **kwds):
        t_begin = time.time()
        result = self.fn(*args, **kwds)
        t_end = time.time()
        print "function = %s" % self.fn.__name__
        print "arguments = {0} {1}".format(args, kwds)
        print "return = {0}".format(result)

        return resultd
     


         
    
def multiplies(x):
    def wrapped(y):
        return x*y 
    return wrapped

@logger
def mult(x,y):
    return x*y 

iter(o[,sentinel]) special trick using the sentinel parameter One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

High Level File Operations

Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment