Skip to content

Instantly share code, notes, and snippets.

@MarcoSero
Last active September 14, 2019 19:44
Show Gist options
  • Save MarcoSero/fd44e4f423fe4114b029be94d1e0a86f to your computer and use it in GitHub Desktop.
Save MarcoSero/fd44e4f423fe4114b029be94d1e0a86f to your computer and use it in GitHub Desktop.
Python's less common constructs and various tips
# Misc python tips from https://book.pythontips.com/en/latest/index.html
###################################################
# *args
def test_var_args(f_arg, *argv):
print("first normal arg:", f_arg)
for arg in argv:
print("another arg through *argv:", arg)
# test_var_args('yasoob', 'python', 'eggs', 'test')
# first with *args
# >>> args = ("two", 3, 5)
# >>> test_args_kwargs(*args)
###################################################
# **kawrgs
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} = {1}".format(key, value))
# >>> greet_me(name="yasoob")
# name = yasoob
# now with **kwargs:
# >>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
# >>> test_args_kwargs(**kwargs)
###################################################
# one line initalizer
class A(object):
def __init__(self, a, b, c, d, e, f):
self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})
###################################################
# decorators
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
###################################################
# decorator classes
class logit(object):
_logfile = 'out.log'
def __init__(self, func):
self.func = func
def __call__(self, *args):
log_string = self.func.__name__ + " was called"
print(log_string)
# Open the logfile and append
with open(self._logfile, 'a') as opened_file:
# Now we log to the specified logfile
opened_file.write(log_string + '\n')
# Now, send a notification
self.notify()
# return base func
return self.func(*args)
def notify(self):
# logit only logs, no more
pass
logit._logfile = 'out2.log' # if change log file
@logit
def myfunc1():
pass
myfunc1()
# Output: myfunc1 was called
###################################################
# try/except/else/finally
try:
print('I am sure no exception is going to occur!')
except Exception:
print('exception')
else:
# any code that should only run if no exception occurs in the try,
# but for which exceptions should NOT be caught
print('This would only run if no exception occurs. And an error here '
'would NOT be caught.')
finally:
print('This would be printed in every case.')
# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs. And an error here would NOT be caught
# This would be printed in every case.
###################################################
# for/else
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
###################################################
# $ pip install virtualenv
# $ virtualenv myproject
# $ source myproject/bin/activate
###################################################
# named tuples
from collections import namedtuple
Animal = namedtuple('Animal', 'name age type')
perry = Animal(name="perry", age=31, type="cat")
print(perry)
# Output: Animal(name='perry', age=31, type='cat')
print(perry.name)
# Output: 'perry'
###################################################
# open file
with open('photo.jpg', 'r+') as f:
jpgdata = f.read()
###################################################
# generators - can implement next()
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
###################################################
# debugging
import pdb
def make_bread():
pdb.set_trace() # sets a breakpoint
return "I don't have time"
# $ python -m pdb my_script.pyc: continue execution
# COMMANDS:
# w: shows the context of the current line it is executing.
# a: print the argument list of the current function
# s: Execute the current line and stop at the first possible occasion.
# n: Continue execution until the next line in the current function is reached or it returns.
###################################################
# context managers
# Context managers allow you to allocate and release resources precisely when you want to
with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')
# custom context manager
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment