


































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!



































































978-1-491-96792-
[LSI]
20 Python Libraries You Aren’t Using (But Should) by Caleb Hattingh
Copyright © 2016 O’Reilly Media Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected].
Editor: Dawn Schanafelt Production Editor: Colleen Lobner Copyeditor: Christina Edwards
Interior Designer: David Futato Cover Designer: Randy Comer Illustrator: Rebecca Demarest
August 2016: First Edition
Revision History for the First Edition 2016-08-08: First Release
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. 20 Python Libra‐ ries You Aren’t Using (But Should), the cover image, and related trade dress are trade‐ marks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limi‐ tation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsi‐ bility to ensure that your use thereof complies with such licenses and/or rights.
CHAPTER 1
Expanding Your
Python Knowledge:
Lesser-Known Libraries
The Python ecosystem is vast and far-reaching in both scope and depth. Starting out in this crazy, open-source forest is daunting, and even with years of experience, it still requires continual effort to keep up-to-date with the best libraries and techniques.
In this report we take a look at some of the lesser-known Python libraries and tools. Python itself already includes a huge number of high-quality libraries; collectively these are called the standard library. The standard library receives a lot of attention, but there are still some libraries within it that should be better known. We will start out by discussing several, extremely useful tools in the standard library that you may not know about.
We’re also going to discuss several exciting, lesser-known libraries from the third-party ecosystem. Many high-quality third-party libraries are already well-known, including Numpy and Scipy, Django, Flask, and Requests; you can easily learn more about these libraries by searching for information online. Rather than focusing on those standouts, this report is instead going to focus on several interesting libraries that are growing in popularity.
Let’s start by taking a look at the standard library.
1
1 Looking for sorted container types? The excellent sorted containers package has high- performance sorted versions of the list, dict, and set datatypes.
The Standard Library
The libraries that tend to get all the attention are the ones heavily used for operating-system interaction, like sys, os, shutil, and to a slightly lesser extent, glob. This is understandable because most Python applications deal with input processing; however, the Python standard library is very rich and includes a bunch of additional functionality that many Python programmers take too long to dis‐ cover. In this chapter we will mention a few libraries that every Python programmer should know very well.
First up we have the collections module. If you’ve been working with Python for any length of time, it is very likely that you have made use of the this module; however, the batteries contained within are so important that we’ll go over them anyway, just in case.
collections.OrderedDict gives you a dict that will preserve the order in which items are added to it; note that this is not the same as a sorted order.^1
The need for an ordered dict comes up surprisingly often. A com‐ mon example is processing lines in a file where the lines (or some‐ thing within them) maps to other data. A mapping is the right solution, and you often need to produce results in the same order in which the input data appeared. Here is a simple example of how the ordering changes with a normal dict:
dict(zip(ascii_lowercase, range(4))) {'a': 0, 'b': 1, 'c': 2, 'd': 3}
dict(zip(ascii_lowercase, range(5))) {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
dict(zip(ascii_lowercase, range(6))) {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'f': 5, 'e': 4}
2 | Chapter 1: Expanding Your Python Knowledge: Lesser-Known Libraries
2 For instance, this example with setdefault() looks like d.setdefault(k, []).append(...). The default value is always evaluated, whereas with defaultdict the default value generator is only evaluated when necessary. But there are still cases where you’ll need setdefault(), such as when using different default values depending on the key.
Here’s a common example:
d = collections.defaultdict(list) d['a'] []
You didn’t create this item yet? No problem! Key lookups auto‐ matically create values using the function provided when creat‐ ing the defaultdict instance.
By setting up the default value as the list constructor in the preced‐ ing example, you can avoid wordy code that looks like this:
d = {} for k in keydata: if not k in d: d[k] = [] d[k].append(...)
The setdefault() method of a dict can be used in a somewhat similar way to initialize items with defaults, but defaultdict gener‐ ally results in clearer code.^2
In the preceding examples, we’re saying that every new element, by default, will be an empty list. If, instead, you wanted every new ele‐ ment to contain a dictionary, you might say defaultdict(dict).
The next tool, collections.namedtuple, is magic in a bottle! Instead of working with this:
tup = (1, True, "red")
You get to work with this:
from collections import namedtuple A = namedtuple('A', 'count enabled color') tup = A(count=1, enabled=True, color="red") tup.count 1 tup.enabled True
4 | Chapter 1: Expanding Your Python Knowledge: Lesser-Known Libraries
tup.color "red" tup A(count=1, enabled=True, color='red')
The best thing about namedtuple is that you can add it to existing code and use it to progressively replace tuples: it can appear any‐ where a tuple is currently being used, without breaking existing code, and without using any extra resources beyond what plain tuples require. Using namedtuple incurs no extra runtime cost, and can make code much easier to read. The most common situation where a namedtuple is recommended is when a function returns multiple results, which are then unpacked into a tuple. Let’s look at an example of code that uses plain tuples, to see why such code can be problematic:
def f(): ... return 2, False, "blue" count, enabled, color = f()
tup = f() enabled = tup[1]
Simple function returning a tuple.
When the function is evaluated, the results are unpacked into separate names.
Worse, the caller might access values inside the returned tuple by index.
The problem with this approach is that this code is fragile to future changes. If the function changes (perhaps by changing the order of the returned items, or adding more items), the unpacking of the returned value will be incorrect. Instead, you can modify existing code to return a namedtuple instance:
def f(): ... # Return a namedtuple! ... return A(2, False, "blue")
count, enabled, color = f()
Even though our function now returns a namedtuple, the same calling code stills works.
The Standard Library | 5
@contextmanager def timing(label: str): t0 = perf_counter() yield lambda : (label, t1 - t0) t1 = perf_counter()
with timing('Array tests') as total: with timing('Array creation innermul') as inner: x = array('d', [0] * 1000000)
with timing('Array creation outermul') as outer: x = array('d', [0]) * 1000000
print ('Total [%s]: %.6f s' % total()) print (' Timing [%s]: %.6f s' % inner()) print (' Timing [%s]: %.6f s' % outer())
The array module in the standard library has an unusual approach to initialization: you pass it an existing sequence, such as a large list, and it converts the data into the datatype of your array if possible; however, you can also create an array from a short sequence, after which you expand it to its full size. Have you ever wondered which is faster? In a moment, we’ll create a timing context manager to measure this and know for sure!
The key step you need to do to make your own context manager is to use the @contextmanager decorator.
The section before the yield is where you can write code that must execute before the body of your context manager will run. Here we record the timestamp before the body will run.
The yield is where execution is transferred to the body of your context manager; in our case, this is where our arrays get cre‐ ated. You can also return data: here I return a closure that will calculate the elapsed time when called. It’s a little clever but hopefully not excessively so: the final time t1 is captured within the closure even though it will only be determined on the next line.
After the yield, we write the code that will be executed when the context manager finishes. For scenarios like file handling, this would be where you close them. In this example, this is where we record the final time t1.
The Standard Library | 7
Here we try the alternative array-creation strategy: first, create the array and then increase size.
For fun, we’ll use our awesome, new context manager to also measure the total time.
On my computer, this code produces this output:
Total [Array tests]: 0.064896 s Timing [Array creation innermul]: 0.064195 s Timing [Array creation outermul]: 0.000659 s
Quite surprisingly, the second method of producing a large array is around 100 times faster than the first. This means that it is much more efficient to create a small array, and then expand it, rather than to create an array entirely from a large list.
The point of this example is not to show the best way to create an array: rather, it is that the contextmanager decorator makes it exceptionally easy to create your own context manager, and context managers are a great way of providing a clean and safe means of managing before-and-after coding tasks.
The concurrent.futures module that was introduced in Python 3 provides a convenient way to manage pools of workers. If you have previously used the threading module in the Python standard library, you will have seen code like this before:
import threading
def work(): return sum(x for x in range(1000000))
thread = threading.Thread(target=work) thread.start() thread.join()
This code is very clean with only one thread, but with many threads it can become quite tricky to deal with sharing work between them. Also, in this example the result of the sum is not obtained from the work function, simply to avoid all the extra code that would be required to do so. There are various techniques for obtaining the result of a work function, such as passing a queue to the function, or subclassing threading.Thread, but we’re not going discuss them
8 | Chapter 1: Expanding Your Python Knowledge: Lesser-Known Libraries
3 CPython means the specific implementation of the Python language that is written in the C language. There are other implementations of Python, created with various other languages and technologies such as .NET, Java and even subsets of Python itself.
Jobs are created, one for every URL in our considerable list. The executor manages the delivery of jobs to the four threads.
This is a simple way of waiting for all the threads to return.
This produces the following output (I’ve shortened the number of results for brevity):
http://www.google.com: length 10560 http://www.twitter.com: length 268924 http://www.facebook.com: length 56667 http://www.youtube.com: length 437754 [snip]
Even though one job is created for every URL, we limit the number of active threads to only four using max_workers and the results are all captured in the results list as they become available. If you wanted to use processes instead of threads, all that needs to change is the first line, from this:
from concurrent.futures import ThreadPoolExecutor as Executor
To this:
from concurrent.futures import ProcessPoolExecutor as Executor
Of course, for this kind of application, which is limited by network latency, a thread-based pool is fine. It is with CPU-bound tasks that Python threads are problematic because of how thread safety has been in implemented inside the CPython^3 runtime interpreter, and in these situations it is best to use a process-based pool instead.
The primary problem with using processes for parallelism is that each process is confined to its own memory space, which makes it difficult for multiple workers to chew on the same large chunk of data. There are ways to get around this, but in such situations threads provide a much simpler programming model. However, as we shall see in “Cython” on page 59, there is a third-party package called Cython that makes it very easy to circumvent this problem with threads.
10 | Chapter 1: Expanding Your Python Knowledge: Lesser-Known Libraries
The logging module is very well known in the web development community, but is far less used in other domains, such as the scien‐ tific one; this is unfortunate, because even for general use, the log‐ ging module is far superior to the print() function. It doesn’t seem that way at first, because the print() function is so simple; however, once you initialize logging, it can look very similar. For instance, compare these two:
print ('This is output to the console')
logger.debug('This is output to the console')
The huge advantage of the latter is that, with a single change to a set‐ ting on the logger instance, you can either show or hide all your debugging messages. This means you no longer have to go through the process of commenting and uncommenting your print() state‐ ments in order to show or hide them. logging also gives you a few different levels so that you can adjust the verbosity of output in your programs. Here’s an example of different levels:
logger.debug('This is for debugging. Very talkative!') logger.info('This is for normal chatter') logger.warning('Warnings should almost always be seen.') logger.error('You definitely want to see all errors!') logger.critical('Last message before a program crash!')
Another really neat trick is that when you use logging, writing mes‐ sages during exception handling is a whole lot easier. You don’t have to deal with sys.exc_info() and the traceback module merely for printing out the exception message with a traceback. You can do this instead:
try : 1/ except : logger.exception("Something failed:")
Just those four lines produces a full traceback in the output:
ERROR:root:Something failed: Traceback (most recent call last): File "logtb.py", line 5, in
The Standard Library | 11
4 Programs that automate some task, often communicating data across different network services like Twitter, IRC, and Slack.
$ python main.py -ll DEBUG
it will run with the logging level set to DEBUG (so all logger messages will be shown), whereas if you run it with
$ python main.py -ll WARNING
it will run at the WARNING level for logging, so all INFO and DEBUG logger messages will be hidden.
There are many more features packed into the logging module, but I hope I’ve convinced you to consider using it instead of using print() for your next program. There is much more information about the logging module online, both in the official Python docu‐ mentation and elsewhere in blogs and tutorials. The goal here is only to convince you that the logging module is worth investigat‐ ing, and getting started with it is easy to do.
There is increasing interest in the creation of bots^4 and other moni‐ toring and automation applications. For these applications, a com‐ mon requirement is to perform actions at specified times or specified intervals. This functionality is provided by the sched mod‐ ule in the standard library. There are already similar tools provided by operating systems, such as cron on Linux and Windows Task Scheduler, but with Python’s own sched module you can ignore these platform differences, as well as incorporate scheduled tasks into a program that might have many other functions.
The documentation for sched is rather terse, but hopefully these examples will get you started. The easy way to begin is to schedule a function to be executed after a specified delay (this is a complete example to make sure you can run it successfully):
import sched import time from datetime import datetime, timedelta
scheduler = sched.scheduler(timefunc=time.time)
def saytime():
The Standard Library | 13
print (time.ctime()) scheduler.enter(10, priority=0, action=saytime)
saytime() try : scheduler.run(blocking=True) except KeyboardInterrupt : print ('Stopped.')
A scheduler instance is created.
A work function is declared, in our case saytime(), which sim‐ ply prints out the current time.
Note that we reschedule the function inside itself, with a ten- second delay.
The scheduler is started with run(blocking=True), and the exe‐ cution point remains here until the program is terminated or Ctrl-C is pressed.
There are a few annoying details about using sched: you have to pass timefunc=time.time as this isn’t set by default, and you have to supply a priority even when not required. However, overall, the sched module still provides a clean way to get cron-like behavior.
Working with delays can be frustrating if what you really want is for a task to execute at specific times. In addition to enter(), a sched instance also provides the enterabs() method with which you can trigger an event at a specific time. We can use that method to trigger a function, say, every whole minute:
import sched import time from datetime import datetime, timedelta
scheduler = sched.scheduler(timefunc=time.time)
def reschedule(): new_target = datetime.now().replace( second=0, microsecond=0) new_target += timedelta(minutes=1) scheduler.enterabs( new_target.timestamp(), priority=0, action=saytime)
def saytime(): print (time.ctime(), flush=True)
14 | Chapter 1: Expanding Your Python Knowledge: Lesser-Known Libraries