Python

Snippets

Generators allow you to define lazy-loaded infinite sequences:

def number_generator():
    i = 0
    while True:
        yield i
        i += 1
numbers = number_generator()
next(numbers)  # 0
next(numbers)  # 1
next(numbers)  # 2
next(numbers)  # 3
#...

Find first item in iterable that satisfies a criterion:

first = next(obj for obj in objs if obj.val==5)

Convert between time formats (source, source):

import datetime
import time

# timestamp to datetime
timestamp = 1545730073
dt_object = datetime.datetime.fromtimestamp(timestamp)

# datetime to timestamp
now = datetime.datetime.now()
timestamp = datetime.datetime.timestamp(now)

# date string to timestamp
s = "01/12/2011"
timestamp = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())

Get list of dictionary keys sorted by their values (source):

numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}
# Use the __getitem__ method as the key function
sorted(numbers, key=numbers.__getitem__)
# In order of sorted values: [1, 2, 3, 4]
['first', 'second', 'third', 'Fourth']

Check of datetime object is localized (source):

d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None

How to use Python's unittest.mock.patch #video - "How to use (and where to apply) Python's unittest.mock.patch in your test suites. In this video I show where to patch, and three ways of applying mock.patch: as a decorator, as a context manager, and inline using mock.patch.start() and mock.patch.stop()."

Is Python pass-by-reference or pass-by-value? #article - " 'Object references are passed by value.' When I first read this smug and overly-pithy definition, I wanted to punch something."

PyCharm #software - IDE. The community edition is free to use, even at work.

Python File I/O #article - "In this article, you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods you should be aware of."

Python's strftime directives - "I need to use Python’s strftime rarely enough that I can’t remember it off the top of my head and never bookmark it but often enough to be annoyed with having to Google “python strftime” and then find the table above in the Python documentation. So I decided to put this reference page up."

SnakeViz #software - "SnakeViz is a browser based graphical viewer for the output of Python’s cProfile module and an alternative to using the standard library pstats module. It was originally inspired by RunSnakeRun. SnakeViz works on Python 2.7 and Python 3. SnakeViz itself is still likely to work on Python 2.6, but official support has been dropped now that Tornado no longer supports Python 2.6."

Traps for the Unwary in Python’s Import System #article - "Python’s import system is powerful, but also quite complicated. Until the release of Python 3.3, there was no comprehensive explanation of the expected import semantics, and even following the release of 3.3, the details of how sys.path is initialised are still somewhat challenging to figure out."

Books

Elegant SciPy by Juan Nunez-Iglesias, Stefan van der Walt & Harriet Dashnow

Flask Web Development by Miguel Grinberg

Fluent Python by Luciano Ramalho

The Hitchhiker's Guide to Python by Kenneth Reitz & Tanya Schlusser

Introducing Python by Bill Lubanovic

Natural Language Processing with Python by Steven Bird, Ewan Klein, Edward Loper - "This book offers a highly accessible introduction to natural language processing, the field that supports a variety of language technologies, from predictive text and email filtering to automatic summarization and translation. With it, you'll learn how to write Python programs that work with large collections of unstructured text. You'll access richly annotated datasets using a comprehensive range of linguistic data structures, and you'll understand the main algorithms for analyzing the content and structure of written communication."

Python Data Science Handbook by Jake VanderPlas

Test-Driven Development with Python by Harry J.W. Percival

Think Bayes by Allen B. Downey

Think Python, 2nd Edition by Allen B. Downey

Thoughtful Machine Learning with Python by Matthew Kirk

Twisted Network Programming Essentials by Jessica McKellar & Abe Fettig

Web Scraping with Python by Ryan Mitchell

matplotlib

Matplotlib trendline #article - "Drawing a trendline of a scatter plot in matplotlib is very easy thanks to numpy’s polyfit function."

pytz

List of tz database time zones #article - Wikipedia. "This is a list of time zones from release 2017c of the tz database."

pytz on pypi - "pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo)."

pytz - World Timezone Definitions for Python #article - Docs. "pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo)."

Time Zone Database - IANA. "The Time Zone Database (often called tz or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules. Its management procedure is documented in BCP 175: Procedures for Maintaining the Time Zone Database."

tz database #article - Wikipedia. "The tz database is a collaborative compilation of information about the world's time zones, primarily intended for use with computer programs and operating systems.[2] Paul Eggert is its current editor and maintainer,[3] with the organizational backing of ICANN.[4] The tz database is also known as tzdata, the zoneinfo database or IANA time zone database, and occasionally as the Olson database, referring to the founding contributor, Arthur David Olson.[5]"

Last updated