├── .gitignore ├── README.md ├── argparse ├── __init__.py ├── adv_cmd_line.py └── simple_cmd_line.py ├── lists ├── __init__.py └── looping_dif_size_lists.py └── threading ├── __init__.py └── producer_consumer_queue.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Morsels # 2 | 3 | Small snippets of code to show common design patterns in Python. 4 | 5 | The code is organized by directories that should make sense. 6 | 7 | ### License: ### 8 | MIT 9 | -------------------------------------------------------------------------------- /argparse/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nryoung/python_morsels/3755cffb7b659d3e4f57722dd9fd5066c696665f/argparse/__init__.py -------------------------------------------------------------------------------- /argparse/adv_cmd_line.py: -------------------------------------------------------------------------------- 1 | """ 2 | Advanced examples of how to use argparse. 3 | """ 4 | import argparse 5 | 6 | def run(): 7 | # instantiate the parser 8 | parser = argparse.ArgumentParser(description='Calculate X to the power of Y') 9 | 10 | # instantiate a group that allows to specify optional options that conflict 11 | group = parser.add_mutually_exclusive_group() 12 | group.add_argument('-v', '--verbose', action='store_true') 13 | group.add_argument('-q', '--quiet', action='store_true') 14 | 15 | # add the positional arguments as well 16 | parser.add_argument('x', type=int, help='the base') 17 | parser.add_argument('y', type=int, help='the exponent') 18 | 19 | # actually parse the args from the user 20 | args = parser.parse_args() 21 | 22 | answer = args.x ** args.y 23 | 24 | # simply access the args like instance attributes 25 | if args.quiet: 26 | print answer 27 | elif args.verbose: 28 | print '{} to the power {} equals {}'.format(args.x, args.y, answer) 29 | else: 30 | print '{}^{} == {}'.format(args.x, args.y, answer) 31 | 32 | if __name__ == '__main__': 33 | run() 34 | -------------------------------------------------------------------------------- /argparse/simple_cmd_line.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple example of how to use the argparse library. 3 | """ 4 | import argparse 5 | 6 | def run(): 7 | # instantiate our argument parser 8 | parser = argparse.ArgumentParser() 9 | 10 | # add an optional and positional arguments to our instantiated parser 11 | parser.add_argument('square', type=int, 12 | help='display a square of a given number') 13 | parser.add_argument('-v', '--verbosity', action='count', default=0, 14 | help='increase output verbosity') 15 | 16 | # actually parse the arguments feed in from the user 17 | args = parser.parse_args() 18 | 19 | # simply access the arguments we want like instance attributes 20 | answer = args.square ** 2 21 | 22 | # here again we access the arguments like instance attributes 23 | if args.verbosity >= 2: 24 | print 'The square of {} equals {}'.format(args.square, answer) 25 | elif args.verbosity >= 1: 26 | print '{}^2 == {}'.format(args.square, answer) 27 | else: 28 | print answer 29 | 30 | if __name__ == '__main__': 31 | run() 32 | -------------------------------------------------------------------------------- /lists/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nryoung/python_morsels/3755cffb7b659d3e4f57722dd9fd5066c696665f/lists/__init__.py -------------------------------------------------------------------------------- /lists/looping_dif_size_lists.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of looping multiple lists of different lengths concurrently 3 | until all are exhausted. 4 | """ 5 | 6 | if __name__ == '__main__': 7 | l = range(10) 8 | m = ['a', 'b', 'c', 'd', 'e'] 9 | n = ['one', 'two', 'three'] 10 | 11 | for e in map(None, l, m, n): 12 | # None is mapped in place of exhausted lists 13 | print e[0] 14 | 15 | if e[1] != None: 16 | print e[1] 17 | if e[2] != None: 18 | print e[2] 19 | 20 | -------------------------------------------------------------------------------- /threading/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nryoung/python_morsels/3755cffb7b659d3e4f57722dd9fd5066c696665f/threading/__init__.py -------------------------------------------------------------------------------- /threading/producer_consumer_queue.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multi Threading example to show a common Producer/Consumer paradigm. 3 | """ 4 | import threading 5 | import Queue 6 | 7 | 8 | class Producer(threading.Thread): 9 | """ 10 | Producer class that takes the raw data and performs some work on it. 11 | Once this work is complete it puts the resultant data in to the out queue 12 | for the Consumer class. 13 | """ 14 | def __init__(self, in_queue, out_queue): 15 | threading.Thread.__init__(self) 16 | self.in_queue = in_queue 17 | self.out_queue = out_queue 18 | 19 | def run(self): 20 | while True: 21 | #grab the data from the in queue 22 | item = self.in_queue.get() 23 | 24 | #here we should do some work with item 25 | #and then put the new data in the out queue 26 | result = 'You should be doing work.' 27 | self.out_queue.put(result) 28 | 29 | #signal that the worker task is done 30 | self.in_queue.task_done() 31 | 32 | class Consumer(threading.Thread): 33 | """ 34 | Consumer class that takes the data outputted by the Producer class and 35 | consumes the data from the out queue and outputs a meaningful result. 36 | """ 37 | def __init__(self, out_queue): 38 | threading.Thread.__init__(self) 39 | self.out_queue = out_queue 40 | 41 | def run(self): 42 | while True: 43 | #grab the data from the out queue 44 | item = self.out_queue.get() 45 | 46 | #here we should consume the item and 47 | #turn it in to whatever output we desire 48 | result = 'This is your awesome output.' 49 | 50 | #signal that the consumer task is done 51 | self.out_queue.task_done() 52 | 53 | if __name__ == '__main__': 54 | 55 | #Create the queues and list to be used 56 | item_list = ['item1', 'item2', 'item3'] 57 | in_queue = Queue.Queue() 58 | out_queue = Queue.Queue() 59 | 60 | #spawn our producer threads and start work 61 | for i in xrange(len(item_list)): 62 | t = Producer(in_queue, out_queue) 63 | t.daemon = True 64 | t.start() 65 | 66 | #put the items in queue 67 | for item in item_list: 68 | in_queue.put(item) 69 | 70 | 71 | #spawn our consumer threads and start consuming 72 | for i in xrange(len(item_list)): 73 | t = Consumer(out_queue) 74 | t.daemon = True 75 | t.start() 76 | 77 | #now block until all data has been processed in 78 | #both queues 79 | in_queue.join() 80 | out_queue.join() 81 | --------------------------------------------------------------------------------