Entradas

Mostrando entradas de diciembre, 2017

Decorators/wrappers

Decorators/wrappers  What is it? 1 Related concepts 2 First class function (FCC) 3 References 4 Closure 4 When do we have a closure? 5 References 5 Videos 5 Blogs 5  What is it? In object-oriented programming , the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern ) is a design pattern that allows behavior to be added to an individual object , either statically or dynamically, without affecting the behavior of other objects from the same class . For example and motivation see: https://en.wikipedia.org/wiki/Decorator_pattern#Motivation Example for my case: # Decorators from functools import wraps def my_logger(orig_func):    import logging    logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)    @wraps(orig_func)    def wrapper(*args, **kwargs):        logging.info(            'Ran with args: {}, and kwargs: {}'.format(args, kwargs))    

How to create a function in python to be used from the terminal

Imagen
To write a python code able to read variables or inputs from the command line you only have to use sys.argv. Let's see a couple of examples. You can find the code here . File called example_v1.py: import sys def main(): print sys.argv if (__name__ == "__main__"): main(); Then you go to the folder where you have it and run this comman in the comman line: python example_v1.py Like here: As you can see the output is the name of the file. Let's try this: python example_v1.py hi hola ciao Basically the comand sys.argv is giving us a list of the commandline arguments received. Now I am going to create a program that is going to say hi and the name that you introduce after file name in the commandline. I called this script example_v2.py: import sys def main(): print 'Hi ' + sys.argv[1] + '!' if (__name__ == "__main__"): main(); So now we can write in the terminal: python