<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Python Supply - Medium]]></title>
        <description><![CDATA[Examples and tutorials that illustrate concepts in an accessible way using the Python programming language. - Medium]]></description>
        <link>https://medium.com/python-supply?source=rss----ef71c9b0089---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Python Supply - Medium</title>
            <link>https://medium.com/python-supply?source=rss----ef71c9b0089---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/python-supply" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Strings, Regular Expressions, and Text Data Analysis]]></title>
            <link>https://medium.com/python-supply/strings-regular-expressions-and-text-data-analysis-718df0886ef1?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/718df0886ef1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Mon, 28 Dec 2020 04:25:20 GMT</pubDate>
            <atom:updated>2020-12-28T04:25:20.168Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you would like to construct a data set of short definitions and facts drawn from a large text corpus such as the set of all article abstracts found in the English-language edition of Wikipedia. You would also like the workflow you assemble to be reusable and flexible, allowing you to update the data set and/or enhance its capabilities quickly. What Python features and libraries, both built-in and from the broader community, can you use to accomplish this?</p><p>While built-in string methods have limited flexibility and regular expressions have limited expressive power, both can still be leveraged in creative ways to implement scalable workflows that process and analyze text data. This article explores these tools and introduces a few useful peripheral packages and techniques within the context of the use case described above.</p><h3>Retrieving and Reading the Raw Data</h3><p>Archives containing all abstracts found in the English-language edition of Wikipedia are regularly updated and available at <a href="https://dumps.wikimedia.org/enwiki/latest/">https://dumps.wikimedia.org/enwiki/latest/</a> (a link you can find via <a href="https://en.wikipedia.org/wiki/Wikipedia:Database_download">this landing page</a>). You decide to use the consolidated abstracts archive file containing all of the abstracts. How can you retrieve it in an automated manner? One way to retrieve a large file that is available online while also getting user-friendly feedback about progress is to use the <a href="https://requests.readthedocs.io/en/master/">requests</a> library together with the <a href="https://pypi.org/project/tqdm/">tqdm</a> library.</p><p>The tqdm library makes it possible to display an animated progress bar while an instance of an <a href="https://docs.python.org/3/glossary.html#term-iterable">iterable</a> data structure emits each of its elements. The example below illustrates the output. The position and leave parameters ensure that the progress bar is not interrupted by newline characters if the output is being displayed within Jupyter Notebook.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>import </strong>tqdm<br><strong>&gt;&gt;&gt;</strong> <strong>import </strong>time<br><strong>&gt;&gt;&gt;</strong> <strong>for </strong>i <strong>in </strong>tqdm.tqdm(range(3), position=0, leave=<strong>True</strong>):<br>...     time.sleep(1)<br>...<br>100%|███████████████████████| 3/3 [00:03&lt;00:00,  1.01s/it]</pre><p>The <a href="https://requests.readthedocs.io/en/master/">requests</a> library makes it possible to create an iterable stream of the data from a file that is located at a specified URL by setting the <a href="https://requests.readthedocs.io/en/master/user/advanced/#body-content-workflow">stream</a> parameter to True. You can then retrieve the data in chunks and <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files">write them to a file</a> while displaying progress to the user. In the example below, the total parameter supplied to tqdm.tqdm is the number of 1 MB (<em>i.e.</em>, 1024² byte) chunks of data in the file; it is determined by dividing file size indicated in the HTTP <a href="https://requests.readthedocs.io/en/master/user/quickstart/#response-headers">response header</a> by the chosen chunk_size of 1 MB.</p><pre><strong>&gt;&gt;&gt;</strong> import requests<br><strong>&gt;&gt;&gt;<br>&gt;&gt;&gt;</strong> url = &quot;https://dumps.wikimedia.org/&quot;<br><strong>&gt;&gt;&gt;</strong> url += &quot;strings-regular-expressions-and-text-data-analysis/&quot;<br><strong>&gt;&gt;&gt;</strong> url += &quot;enwiki-20191120-abstract-sample.xml.gz&quot;<br><strong>&gt;&gt;&gt;</strong><br><strong>&gt;&gt;&gt; with </strong>requests.get(url, stream=True) <strong>as </strong>response:<br><strong>...     </strong>file_size = int(response.headers[&#39;Content-length&#39;])<strong><br>...     </strong>chunk_size = 1024*1024<strong><br>...</strong>     <strong>with </strong>open(&quot;abstracts.xml.gz&quot;, &quot;wb&quot;) <strong>as </strong>file:<br><strong>...</strong>         chunks = response.iter_content(chunk_size=chunk_size)<br><strong>...</strong>         <strong>for </strong>chunk <strong>in </strong>tqdm.tqdm(<br><strong>...</strong>                 chunks, total=ceil(file_size/chunk_size),<strong><br>...</strong>                 position=0, leave=True<br><strong>...</strong>             ):<br><strong>...</strong>             file.write(chunk)<br>...<br>100%|████████████████████████| 10/10 [00:06&lt;00:00,  1.89it/s]</pre><p>Once you have the compressed file abstracts.xml.gz on your disk, you can open it and iterate over the data by uncompressing it one line at a time using the built-in <a href="https://docs.python.org/3/library/gzip.html">gzip</a> library. Below, the total number of lines in the file is counted using a comprehension and the built-in <a href="https://docs.python.org/3/library/functions.html#sum">sum</a> function.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>import </strong>gzip<br><strong>&gt;&gt;&gt;</strong> <strong>with </strong>gzip.open(&quot;abstracts.xml.gz&quot;) <strong>as </strong>file:<br>...     print(sum(1 <strong>for </strong>line <strong>in </strong>file))<br>...<br>238564</pre><h3>Processing Raw String Data with String Functions</h3><p>Given that the data set is in XML format, the most general approach to parsing it is to use an XML parser such as <a href="https://pypi.org/project/lxml/">lxml</a>. However, in this case the text content in the file follows a consistent format: the text for each abstract appears on its own line in its entirety, surrounded by the two element delimiters &lt;abstract&gt; and &lt;/abstract&gt;. Thus, you can iterate over every line in the file and determine whether or not you want to extract it. You divide this workflow into two steps: extracting the lines, and then extracting the abstracts themselves.</p><p>First, you decide to implement a <a href="https://docs.python.org/3/glossary.html#term-generator">generator</a> that iterates over all the lines in the file and yields them one at a time. In case the text data on a particular line has an unknown encoding, the <a href="https://pypi.org/project/chardet/">chardet</a> library is used to check each line. This is not likely to be an issue in this particular data set, but allowing only those lines that are valid <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> or <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> can help you avoid any unexpected issues later in the process. Before yielding it, you convert each line from binary data into a string using the <a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode">decode</a> method of the binary data type <a href="https://docs.python.org/3/library/stdtypes.html#bytes">bytes</a> and then remove any whitespace at the beginning or end of the string using <a href="https://docs.python.org/3/library/stdtypes.html#str.strip">strip</a>.</p><pre><strong>from </strong>chardet <strong>import </strong>detect<br><strong>def </strong>lines():<br>    <strong>with</strong> gzip.open(&quot;abstracts.xml.gz&quot;) <strong>as </strong>file:<br>        <strong>for </strong>line <strong>in </strong>file:<br>            <strong>if </strong>detect(line)[&quot;encoding&quot;] <strong>in </strong>[&#39;ascii&#39;, &#39;utf-8&#39;]:<br>                <strong>yield </strong>line.decode().strip()</pre><p>How do you extract the actual text of an abstract from each line of the form &lt;abstract&gt;...&lt;/abstract&gt;? You can take advantage of the <a href="https://docs.python.org/3/library/stdtypes.html#str.startswith">startswith</a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.endswith">endswith</a> built-in string methods to identify these lines, and then you can use string <a href="https://docs.python.org/3/tutorial/introduction.html?highlight=string%20slice#strings">slice indices</a> to extract the raw text of each abstract. The function below defines a <a href="https://docs.python.org/3/glossary.html#term-generator">generator</a> that yields every abstract that appears on any line in the compressed file.</p><pre><strong>def </strong>abstracts():<br>    <strong>for </strong>line <strong>in </strong>lines():<br>        <strong>if </strong>line.startswith(&quot;&lt;abstract&gt;&quot;) <strong>and</strong>\<br>           line.endswith(&quot;&lt;/abstract&gt;&quot;):<br>            line = line[len(&quot;&lt;abstract&gt;&quot;):-len(&quot;&lt;/abstract&gt;&quot;)]<br>            <strong>yield </strong>line</pre><p>You can use the <a href="https://docs.python.org/3/library/itertools.html#itertools.islice">islice</a> function for iterable data structure instances to iterate over only a portion of the abstracts. The line below calculates the maximum length of the first 100 abstracts.</p><pre><strong>&gt;&gt;&gt; from </strong>itertools <strong>import </strong>islice<strong><br>&gt;&gt;&gt; </strong>max(len(a) <strong>for </strong>a <strong>in </strong>islice(abstracts(), 0, 100))<br>553</pre><h3>Extracting Strings with a Specific Structure</h3><p><a href="https://en.wikipedia.org/wiki/Regular_expression">Regular expressions</a> are mathematical constructs that can be used to describe <em>sets of strings</em> that follow a particular pattern or format. The history and conceptual details of regular expressions are far beyond the scope of this article, but you only need to understand a few basic building blocks to begin using the built-in <a href="https://docs.python.org/3/library/re.html">re</a> library to identify when a string adheres to a specific pattern.</p><p>In Python, regular expressions are represented as strings. In the example below, the regular expression &quot;abc&quot; is satisfied only by those strings that begin with the exact sequence of characters abc. To check whether a string satisfies a regular expression, it is sufficient to compile the regular expression string using <a href="https://docs.python.org/3/library/re.html#re.compile">compile</a> and then to use the <a href="https://docs.python.org/3/library/re.html#re.match">match</a> method to perform the check.</p><pre><strong>&gt;&gt;&gt; import </strong>re<br><strong>&gt;&gt;&gt;</strong> re.compile(&quot;abc&quot;).match(&quot;abcd&quot;)<br>&lt;re.Match object; span=(0, 3), match=&#39;abc&#39;&gt;</pre><p>To ensure that only an entire string (as opposed to only a portion of the string) can satisfy a regular expression, it is possible to add ^ to the beginning of the regular expression and $ to the end.</p><pre><strong>&gt;&gt;&gt; </strong>re.compile(&quot;^abc$&quot;).match(&quot;abc&quot;)<br>&lt;re.Match object; span=(0, 3), match=&#39;abc&#39;&gt;<br><strong>&gt;&gt;&gt;</strong> re.compile(&quot;^abc$&quot;).match(&quot;abcd&quot;)<br><strong>None</strong></pre><p>The <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax">syntax for regular expression strings</a> consists of a large collection of special characters and character sequences. For the purposes of the motivating example, the below syntactic constructs are sufficient:</p><ul><li>[a-z] is satisfied by any lowercase single letter;</li><li>\s is satisfied by any single whitespace character and \. is satisfied by a period;</li><li>given any regular expression r, the set of strings that satisfy r also satisfy (r) and vice versa;</li><li>given any regular expression r, the set of strings that satisfy r* consists of all strings that are concatenations of zero or more individual strings that each independently satisfy r (<em>e.g.</em>, &quot;abc&quot;, &quot;aaaa&quot;, and &quot;&quot; all satisfy [a-z]*);</li><li>given any two regular expressions r and s, the regular expression r|s is satisfied by any string that satisfies either r, s, or both;</li><li>given any two regular expressions r and s, the regular expression rs is satisfied by any string consisting of a portion that satisfies r followed immediately by a portion that satisfies s (<em>e.g.</em>, &quot;xy&quot; satisfies [a-z][a-z], while &quot;x&quot; and &quot;xyz&quot; do not).</li></ul><p>To make it easier to experiment quickly with larger and more complex regular expressions while reusing common building blocks, you can define functions that take smaller expressions and build larger ones. Because regular expressions are represented using Python strings, you can use string methods such as <a href="https://docs.python.org/3/library/stdtypes.html#str.join">join</a> to accomplish this. The functions below also use <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists">argument unpacking syntax</a> to make code that invokes them more concise.</p><pre><strong>def </strong>atom(s):<br>    <em># Wrap an expression in parenthesis.</em><br>    <strong>return </strong>&quot;(&quot; + s + &quot;)&quot;</pre><pre><strong>def </strong>options(*rs):<br>    <em># Given expressions r1, r2, ..., rN, build<br>    # the expression (r1)|(r2)|...|(rN).</em><br>    <strong>return </strong>atom(&quot;|&quot;.join([atom(r) <strong>for </strong>r <strong>in </strong>rs]))</pre><pre><strong>def </strong>adjacent(*rs):<br>    <em># Given expressions r1, r2, ..., rN, build<br>    # the expression (r1)(r2)...(rN).</em><br>    <strong>return </strong>atom(&quot;&quot;.join([atom(r) <strong>for </strong>r <strong>in </strong>rs]))</pre><pre><strong>def </strong>spaced(*rs):<br>    <em># Given expressions r1, r2, ..., rN, build<br>    # the expression (r1)\s(r2)\s...\s(rN).</em><br>    <strong>return </strong>atom(&quot;\s&quot;.join([atom(r) <strong>for </strong>r <strong>in </strong>rs]))</pre><pre><strong>def </strong>repeated(r):<br>    <em># Given the expression r0, build ((r0)*).</em><br>    <strong>return </strong>atom(atom(r) + &quot;*&quot;)</pre><pre><strong>def </strong>repeated_spaced(r):<br>    <em># Given the expression r0, build (((r0)(\s))*(r0)).</em><br>    <strong>return </strong>adjacent(repeated(adjacent(r, &quot;\s&quot;)), r)</pre><p>The definitions below are fairly self-explanatory and use the above functions to assemble more complex regular expressions. The below regular expressions, in turn, are useful as building blocks for building a regular expression that matches a sentence of the form you are trying to identify in the data set of abstracts.</p><pre>article = options(&quot;A&quot;, &quot;a&quot;, &quot;An&quot;, &quot;an&quot;, &quot;The&quot;, &quot;the&quot;)<br>word = atom(&quot;[a-z]+&quot;)<br>verb = options(&quot;are&quot;, &quot;is&quot;)<br>period = atom(&quot;\.&quot;)</pre><p>The definition below is for a regular expression that is satisfied by any string that (1) begins with a definite or indefinite article, (2) has any non-zero number of words following the article, (3) has a linking verb followed by one or more additional words, and (4) ends with a period.</p><pre>sentence = adjacent(<br>    spaced(<br>        article, word, repeated_spaced(word),<br>        verb,<br>        repeated_spaced(word)<br>    ),<br>    period<br>)</pre><p>You can see the actual string that the function invocations above construct. It should be apparent that assembling (or modifying) a string such as the one below manually in its raw form is likely to be an error-prone process. Abstractions such as those above are an effective way to manage complexity in regular expressions.</p><pre><strong>&gt;&gt;&gt;</strong> sentence<br>&#39;((((((A)|(a)|(An)|(an)|(The)|(the)))\\s(([a-z]+))\\s(((((((([a-z]+))(\\s+)))*))(([a-z]+))))\\s(((are)|(is)))\\s(((((((([a-z]+))(\\s+)))*))(([a-z]+))))))((\\.)))&#39;</pre><p>You decide to use this regular expression to identify facts and definitions in the abstracts, storing a reusable compiled version of it as sentence_re for better performance. Before you check whether an abstract matches the regular expression sentence, you use the string method <a href="https://docs.python.org/3/library/stdtypes.html#str.split">split</a> to separate the string into a list of substrings (<em>i.e.</em>, those substrings that are found between the instances of the . character in the string). You then use list index notation to keep only the first entry. Since the split method does not include the character used to split the string, you need to concatenate it back onto the first substring. The example below applies this workflow to a portion of the abstracts.</p><pre><strong>&gt;&gt;&gt;</strong> sentence_re = re.compile(&quot;^&quot; + sentence + &quot;$&quot;)<br><strong>&gt;&gt;&gt;</strong> <strong>for </strong>a <strong>in </strong>itertools.islice(abstracts(), 0, 400):<br><strong>...</strong>     a = a.split(&quot;.&quot;)[0] + &#39;.&#39; <em># Keep only first sentence.</em><br><strong>...</strong>     <strong>if </strong>sentence_re.match(a) <strong>is not None</strong>:<br><strong>...</strong>         print(a)<br><strong>...</strong><br>An audio file format is a file format for storing digital audio data on a computer system.<br>The bell curve is typical of the normal distribution.<br>The immune system is a host defense system comprising many biological structures and processes within an organism that protects against disease.<br>A monolithic kernel is an operating system architecture where the entire operating system is working in kernel space.</pre><h3>Basic Analysis Example</h3><p>You are interested in learning more about the particular terms or phrases being described by the first sentence of each abstract. In particular, you would like to know the distribution of the number of words before the verb. One approach is to use the <a href="https://docs.python.org/3/library/re.html#re.search">search</a> method to find the first instance of a verb and then to inspect the contents of the <a href="https://docs.python.org/3/library/re.html#match-objects">Match object</a> to determine the location of the match. Then it is possible to use the string <a href="https://docs.python.org/3/library/stdtypes.html#str.count">count</a> method on the substring (up to and including that matched verb) to determine the number of spaces (and thus, words) before the first verb.</p><pre><strong>&gt;&gt;&gt; </strong>counts = []<br><strong>&gt;&gt;&gt;</strong> verb_re = re.compile(verb)<br><strong>&gt;&gt;&gt;</strong><br><strong>&gt;&gt;&gt;</strong> <strong>for </strong>abstract <strong>in </strong>tqdm.tqdm(<br>...         abstracts(), position=0, leave=<strong>True</strong>, total=210777<br>...     ):<br>...     abstract = abstract.split(&quot;.&quot;)[0] + &#39;.&#39;<br>...     <strong>if </strong>sentence_re.match(abstract) <strong>is not None</strong>:<br>...         <strong>if </strong>(m := verb_re.search(abstract)) <strong>is not None</strong>:<br>...             counts.append(abstract[:m.end()].count(&quot; &quot;))<br>...<br>100%|███████████████████| 210777/210777 [04:44&lt;00:00, 739.92it/s]</pre><p>You may notice in the above example the use of an <a href="https://www.python.org/dev/peps/pep-0572/">assignment expression</a> involving the := operator. Scenarios such as this one play a significant role in the rationale for this new feature (introduced in Python 3.8). The alternative syntax would have required a separate line for the statement m = verb_re.search(abstract).</p><p>Now that the number of words before the verb in each abstract is in the list of integers counts, it is straightforward to generate a histogram using <a href="https://matplotlib.org/">Matplotlib</a>. The results suggest that the most common case is one involving three words before the verb (which, given that the initial <a href="https://en.wikipedia.org/wiki/Article_(grammar)">definite or indefinite article</a> is also being counted, suggests that most abstracts refer to a concept described by a two-word phrase).</p><pre><strong>import </strong>matplotlib.pyplot <strong>as </strong>plt<br>plt.hist(<br>    counts,<br>    bins=range(max(counts)), density=False, histtype=&quot;bar&quot;,<br>    color=&quot;#DD7600&quot;, edgecolor=&quot;k&quot;, alpha=0.8<br>)<br>plt.ylabel(&quot;number of abstracts&quot;)<br>plt.xlabel(&quot;number of words before verb&quot;)<br>plt.xticks(range(0, max(counts)))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*-EECWD0V43ljzy8746Oo5Q.png" /><figcaption>Histogram visualizing the distribution (across all abstracts of a specific form) of the number of words that occur before the first verb.</figcaption></figure><h3>Further Reading</h3><p>This article reviews a use case while referencing or employing techniques that are drawn from a broad array of disciplines and topic areas: data science (specifically, <a href="https://en.wikipedia.org/wiki/Data_cleansing">data cleaning</a>), <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL</a>, parsing and data structure search and traversal, text data analysis and natural language processing, regular expressions and regular language grammars, web scraping, and a few others. Providing more detailed directions for exploring each of these further is beyond the scope of this article, but a few points that relate specifically to implementing such workflows in Python are worth noting.</p><p>The <a href="https://pypi.org/project/regex/">regex</a> package is backwards-compatible with the built-in <a href="https://docs.python.org/3/library/re.html">re</a> library but offers additional features such as fuzzy matching. The long-lived <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> library is described as a tool for parsing HTML and XML documents (typically in scenarios involving web scraping), but is actually a powerful text data processing tool in its own right. An assortment of sophisticated natural language processing tools and techniques are available in the <a href="https://www.nltk.org/">Natural Language Toolkit</a>, including the ability to tokenize, tag, and parse text. Finally, towards the machine learning end of the spectrum are libraries like <a href="https://radimrehurek.com/gensim/">Gensim</a>, which provide capabilities such as <a href="https://en.wikipedia.org/wiki/Topic_model">topic modeling</a>.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/strings-regular-expressions-and-text-data-analysis/blob/master/strings-regular-expressions-and-text-data-analysis.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/strings-regular-expressions-and-text-data-analysis"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=718df0886ef1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/strings-regular-expressions-and-text-data-analysis-718df0886ef1">Strings, Regular Expressions, and Text Data Analysis</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applications of Immutability]]></title>
            <link>https://medium.com/python-supply/applications-of-immutability-2580266ef57b?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/2580266ef57b</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Sat, 26 Dec 2020 02:23:46 GMT</pubDate>
            <atom:updated>2020-12-27T07:48:28.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are implementing a service that works with data sets that represent routes on a map (<em>e.g.</em>, collections of driving directions or logs of past trips). The road network is represented as a graph with nodes and edges, and each route is conceptually a collection of edges. You are tasked with choosing an appropriate data structure for routes that meets at least the following criteria:</p><ul><li>it should be possible to deduplicate large collections of routes,</li><li>it should be possible to use individual routes as keys into a dictionary (<em>e.g.</em>, to build a cache that maps each route to its total distance or average trip time),</li><li>programmers should not be able to modify a route instance if they obtain a reference to it, and</li><li>the collections of edges found in a route may be supplied to your data structure’s constructor in any order (even though they represent the same route for purposes of caching or deduplication).</li></ul><p>What are your options in implementing a data structure for routes that meets these criteria, and what issues should you consider?</p><p>Both built-in and user-defined data structures in Python can be either mutable or immutable. This article explains why Python makes this distinction for built-in data structures, breaks down the independent characteristics that are often associated with immutable data structures, and explores several approaches you can employ when addressing the above use case.</p><h3>Mutable and Immutable Built-in Types</h3><p>Each of the <a href="https://docs.python.org/3/library/stdtypes.html">built-in types</a> found in Python is either mutable or immutable:</p><ul><li>instances of the collection types <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists">list</a>, <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">dict</a>, and <a href="https://docs.python.org/3/tutorial/datastructures.html#sets">set</a> are mutable,</li><li>instances of the collection types <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences">tuple</a>, <a href="https://docs.python.org/3/library/stdtypes.html#frozenset">frozenset</a>, and <a href="https://docs.python.org/3/library/stdtypes.html#ranges">range</a> are immutable,</li><li>instances of types such as <a href="https://docs.python.org/3/library/functions.html#bool">bool</a>, <a href="https://docs.python.org/3/library/functions.html#int">int</a>, <a href="https://docs.python.org/3/library/functions.html#float">float</a>, and <a href="https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str">str</a> are immutable, and</li><li>instances of <a href="https://docs.python.org/3/library/stdtypes.html#bytes">bytes</a> are immutable but instances of <a href="https://docs.python.org/3/library/stdtypes.html#bytearray">bytearray</a> are mutable.</li></ul><p>Mutable types are accompanied by methods that modify instances of the corresponding data structure in-place (usually returning None) while immutable types are usually accompanied by functions and methods that return a new instance of that type (such as string concatenation). But why does Python distinguish between mutable and immutable built-in types? The reasons are subtle and relate to an interplay between programming language design decisions and practical performance requirements. A brief overview is provided below, and you can find a detailed <a href="https://docs.python.org/3/faq/design.html#why-must-dictionary-keys-be-immutable">answer to this question</a> in the Python documentation.</p><p>Some programming languages such as <a href="https://en.wikipedia.org/wiki/Haskell_(programming_language)">Haskell</a> have only immutable values (and thus all new values are necessarily copies or entirely new objects). One significant benefit of this approach is that code in Haskell is much easier and safer to refactor and transform (<em>e.g.</em>, for purposes of optimization) because the <em>context</em> of an expression will never affect its meaning. As an example, consider the following for loop.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>for </strong>i <strong>in </strong>range(3):<br><strong>...</strong>     x = 1 + 2 + 3 + 4<br>...     print(x)<br><strong>...</strong><br>10<br>10<br>10</pre><p>Because the expression 1 + 2 + 3 + 4 is immutable (<em>i.e.</em>, its value will not change depending on where it appears in a program), it can safely be moved up and outside of the for loop without changing the behavior of the program. Modern interpreters and compilers routinely use such an approach to perform performance optimizations directly on the <a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">abstract syntax tree of the program</a>.</p><pre><strong>&gt;&gt;&gt;</strong> immutable_value = 1 + 2 + 3 + 4<br><strong>&gt;&gt;&gt;</strong> <strong>for </strong>i <strong>in </strong>range(3):<br><strong>...</strong>     x = immutable_value<br>...     print(x)<br><strong>...</strong><br>10<br>10<br>10</pre><p>Python set instances support an extremely fast lookup/membership operation (which can be invoked using the infix <a href="https://docs.python.org/3/library/stdtypes.html#set">in</a> operator) because the Python interpreter builds a <a href="https://en.wikipedia.org/wiki/Hash_table">hash table</a> that contains hashes of all the individual elements of a set. As a reference point, consider the performance when searching for an element in a list.</p><pre><strong>&gt;&gt;&gt;</strong> import time<br><strong>&gt;&gt;&gt;</strong> l = list(range(0,1000000))<br><strong>&gt;&gt;&gt; </strong>start = time.perf_counter()<br><strong>&gt;&gt;&gt;</strong> 999999 in l<br><strong>&gt;&gt;&gt; </strong>time.perf_counter() - start<br>0.07584109995514154</pre><p>When evaluating the in operator in an expression such as 4 in {1, 2, 3, 4, 5}, the interpreter hashes 4 and finds the hash value in the hash table for {1, 2, 3, 4, 5} in nearly constant time. As shown below, this is significantly faster than performing a search through all of the elements in the set as in the above example (which is the only option without some sort of alternative comparison and sorting mechanism).</p><pre><strong>&gt;&gt;&gt;</strong> s = set(l)<br><strong>&gt;&gt;&gt; </strong>start = time.perf_counter()<br><strong>&gt;&gt;&gt;</strong> 999999 in s<br><strong>&gt;&gt;&gt; </strong>time.perf_counter() - start<br>0.00026190001517534256</pre><p>Suppose that elements in a set instance were mutable. This would mean that their hash would also be mutable, which would in term mean that the hash table for the set instance would need to be updated. But how would the interpreter even know to update the hash table? Consider the example below.</p><pre>e = [1, 2, 3]<br>u = {e, &quot;a&quot;}<br>v = {e, True, False}<br>w = {e, 1.2, 2.3, 3.4}<br>e.pop()</pre><p>Every time a statement such as e.pop() is executed, the interpreter would need to check whether e is a member of any sets (there are three such sets in this case) and would need to update the hash table for <em>every</em> one of them to accurately reflect that the hash value corresponding to e is different. If the interpreter <em>did not</em> do this, then an expression such as [1, 2, 3] in u could not be evaluated both correctly and efficiently.</p><p>It is worth noting that Python’s set and dict data structures were intentionally designed this way under an assumption: programmers will usually want to perform lookup in set and dict instances based on the <em>value</em> and not the <em>particular instance</em> of a data structure. An alternate approach <em>could</em> have been to simply build the hash table using the memory address of the each element rather than its value. However, this approach begins to fall apart as soon as strings are used as elements: after the statements k = &quot;abc!&quot; and d = {&quot;abc!&quot;: 123}, a programmer probably expects d[k] == 123 to be True even though the address of the string instance &quot;abc!&quot; in k = &quot;abc!&quot; is <em>different</em> from the address of the distinct string instance &quot;abc&quot; in d = {&quot;abc!&quot;: 123}. This can be confirmed using the built-in <a href="https://docs.python.org/3/library/functions.html#id">id</a> function (though you should be aware of <a href="https://docs.python.org/3/library/sys.html#sys.intern">interning</a> to avoid confusion when testing your own examples).</p><pre><strong>&gt;&gt;&gt;</strong> k = &quot;abc!&quot;<br><strong>&gt;&gt;&gt; </strong>d = {&quot;abc!&quot;: 123}<br><strong>&gt;&gt;&gt; </strong>id(k) == id(list(d.keys())[0])<br><strong>False</strong></pre><p>The above explains why built-in immutable types exist and why Python requires them in certain contexts. This also indicates that to satisfy the criteria in the motivating scenario described in the introduction, the data structure you define for representing a route must be one that Python recognizes as being immutable.</p><h3>Defining an Immutable Data Structure</h3><p>In Python, there are a number of approaches available to you when you are defining a data structure for a use case such as the one described in the introduction.</p><ul><li>One approach is simply to adopt a <em>convention</em> of using an existing built-in type to represent instances of your data structure. For example, a route can be represented as a <a href="https://docs.python.org/3/library/stdtypes.html#frozenset">frozenset</a> of <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences">tuple</a> instances (with two <a href="https://docs.python.org/3/library/functions.html#int">int</a> components in each tuple representing the endpoints of the edge). This may be advantageous if you are trying to avoid unnecessary clutter or would like to make it easier for other libraries or components to use your data without dealing with (or introducing within their own code) application-specific boilerplate.</li><li>A second approach is to define a derived class that <a href="https://docs.python.org/3/tutorial/classes.html#inheritance">inherits</a> the features of a built-in type (as demonstrated in an <a href="https://medium.com/python-supply/embedded-languages-via-overloading-ac942c18a65b">another article on operator overloading</a>). This has most of the benefits of the first approach above, but gives you more control over the interface of the data structure. This is useful if you would like to add custom methods, to modify how certain default methods inherited from the built-in type behave, to <a href="https://lapets.medium.com/static-checking-via-metaclasses-cec368765b58">enforce type or value constraints on method arguments</a>, to throw application-specific exceptions, or simply to provide more user-friendly and application-specific synonyms for existing functions and methods.</li><li>A third approach is to define a brand new class that conceals its internal representation. This has the benefit of encapsulation (allowing you to modify the internal representation of the actual route in the future), but requires a more careful approach on the conceptual side and more boilerplate code on the practical side.</li></ul><h4>Using Built-in Types</h4><p>A route could be represented using an instance of frozenset containing instances of tuple (with each tuple representing one edge) that in turn each contain two integers (with each integer representing one of the two nodes that an edge connects). Because integers and tuples are immutable, they can be elements inside frozenset instances.</p><pre><strong>&gt;&gt;&gt;</strong> route_one = frozenset({(0, 1), (1, 2), (2, 3)})<br><strong>&gt;&gt;&gt;</strong> route_two = frozenset({(1, 2), (0, 1), (2, 3)})<br><strong>&gt;&gt;&gt;</strong> len({route_one, route_two}) <em># Two routes with the same edges.</em><br>1</pre><p>Because frozenset instances are immutable, all four criteria for the route data structure can be satisfied. In particular, routes can be deduplicated by inserting them into a set and a mapping from routes to their distances can be implemented using a dict. Because a frozenset behaves like a mathematical set, the order of the edges does not matter.</p><pre><strong>&gt;&gt;&gt;</strong> distances = {route_one: 3} <em># No exception is raised.</em><br><strong>&gt;&gt;&gt;</strong> len({route_one, route_two}) <em># Deduplication occurs.</em><br>1</pre><p>Note that an instance of an immutable type <em>can</em> contain a mutable object inside it. However, in order for a value to be used as a key in a dict instance or an element in a set instance, all elements inside the immutable type must also be immutable (and so on, down to the leaves of the data structure instance). In the example below, the mutable object [True, False] causes an exception even though it is inside an immutable frozenset instance that is itself inside an immutable tuple instance.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>try</strong>:<br><strong>...</strong>     {tuple(&quot;a&quot;, frozenset({[True, False]})): 0}<br><strong>...</strong> <strong>except </strong>Exception <strong>as </strong>e:<br><strong>...</strong>     print(e)<br><strong>...</strong><br>unhashable type: &#39;list&#39;</pre><h4>Defining a Derived Class</h4><p>It is possible to take advantage of Python’s support for <a href="https://docs.python.org/3/tutorial/classes.html#inheritance">inheritance</a> to define a class that is <em>derived</em> from one of the immutable types. This ensures that the derived class has the same attributes and methods as the base class. In the example below, the route class inherits all the features of frozenset. In addition, it has a method distance that computes the distance of the route (defined as the number of hops that occur between two distinct nodes) and a custom definition of <a href="https://docs.python.org/3/library/functions.html#repr">__repr__</a> to display an instance in a friendly way.</p><pre><strong>class </strong>route(frozenset):<br>    <strong>def </strong>distance(self):<br>        <strong>return </strong>sum([1 <strong>for </strong>e <strong>in </strong>self <strong>if </strong>e[0] != e[1]])<br>    <br>    <strong>def </strong>__repr__(self):<br>        <strong>return </strong>&quot;route({&quot; + &quot;, &quot;.join([str(e) <strong>for </strong>e <strong>in </strong>self]) + &quot;})&quot;</pre><p>To create an instance of route, it is sufficient to wrap an instance of frozenset with the constructor.</p><pre><strong>&gt;&gt;&gt;</strong> route({(0,0), (0,1), (1,1)}).distance()<br>1</pre><p>With respect to its immutability, instances of route can be used in any context in which frozenset can be used.</p><pre><strong>&gt;&gt;&gt;</strong> {route({(0,1), (1,2)}): 2}<br>{route({(0, 1), (1, 2)}): 2}</pre><p>If your data structure were simpler (<em>e.g.</em>, a record with a fixed collection of named attributes), you could have your derived class inherit from a type generated using <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple">namedtuple</a> from the built-in <a href="https://docs.python.org/3/library/collections.html">collections</a> library.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>from </strong>collections <strong>import </strong>namedtuple<br><strong>&gt;&gt;&gt; class </strong>record(namedtuple(&quot;record&quot;, &quot;name age&quot;)):<br>...     <strong>pass</strong><br><strong>...<br>&gt;&gt;&gt; </strong>record(&quot;Alice&quot;, 32)<br>record(name=&#39;Alice&#39;, age=32)</pre><h4>Defining a New Class</h4><p>When creating your own class for the route data structure, you first need to determine which characteristics of built-in immutable types you would like your class to possess.</p><ol><li>If you would like to be able to use instances of the class inside a set instance or as a key in a dict instance, you must define appropriate methods to make this possible.</li><li>If you would like to ensure that it is not possible to modify or extend an instance of your class once it has been created, you will need to redefine specific methods and attributes in a particular way. However, it is worth noting that this approach does not enforce immutability to the same extent as the approach of defining a class derived from an immutable type.</li></ol><p>To satisfy the first requirement, it is sufficient to provide definitions for the <a href="https://docs.python.org/3/reference/datamodel.html#object.__hash__">__hash__</a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__</a> methods. The Python interpreter will invoke these methods when building a hash table (<em>e.g.</em>, for a set or dict instance) as well as when retrieving a value. The __eq__ method is required in addition to the __hash__ method because hashes are not guaranteed to be unique and the interpreter needs to be able to disambiguate between objects of your class in such scenarios. Note that the Python interpreter expects that two values that are equal according to __eq__ must have the same hash values according to __hash__.</p><pre><strong>class </strong>route():<br>    <strong>def </strong>__init__(self, edges):<br>        self.es = edges</pre><pre>    <strong>def </strong>__hash__(self):<br>        es = sorted(list(set(self.es)))<br>        <strong>import </strong>hashlib<br>        <strong>return </strong>int(hashlib.sha256(str(es).encode()).hexdigest(), 16)</pre><pre>    <strong>def </strong>__eq__(self, other):<br>        <strong>return </strong>set(self.es) == set(other.es)</pre><pre>    <strong>def </strong>distance(self):<br>        <strong>return </strong>sum([1 <strong>for </strong>e <strong>in </strong>self.es <strong>if </strong>e[0] != e[1]])</pre><p>It is now possible to use instances of route as elements of set instances and as keys for dict instances.</p><pre><strong>&gt;&gt;&gt; </strong>route_one = route([(0,0), (0,1), (1,1)])<br><strong>&gt;&gt;&gt; </strong>route_two = route([(0,1), (1,2), (2,3)])<br><strong>&gt;&gt;&gt; </strong>route_three = route([(0,1), (1,2), (2,3)])<br><strong>&gt;&gt;&gt; </strong>distances = {route_one: 3}<br><strong>&gt;&gt;&gt; </strong>len({route_one, route_two, route_three})<br>2</pre><p>Note that in the definition of the __hash__ method, a cryptographic hash function sha256 from the built-in <a href="https://docs.python.org/3/library/hashlib.html">hashlib</a> library is applied to a string version of a normalized representation (<em>i.e.</em>, sorted and deduplicated) of a route. Normalization ensures that the order and multiplicity of edges does not change the hash of a route. Use of sha256 ensures that the hash of any instance of the same string will always be the same in any environment and under any version of Python. This is not guaranteed by the built-in <a href="https://docs.python.org/3/library/functions.html#hash">hash</a> function, which may return different results across different Python sessions (even in the same environment). Such an inconsistency could be an issue if, for example, users of your data structure store instances of it on disk and load them again at a later time.</p><p>One way to satisfy the requirement that users cannot modify or extend instances of your data structure is to explicitly set the <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__slots__#object.__slots__">__slots__</a> attribute to a tuple containing only those attributes that you require for your implementation.</p><pre><strong>class </strong>route():<br>    __slots__ = (&quot;es&quot;)<br>    <br>    <strong>def </strong>__init__(self, edges):<br>        self.es = edges</pre><p>It is now not possible to create new attributes for any route instance.</p><pre><strong>&gt;&gt;&gt; try</strong>:<br>...     route_example = route([(0,1), (1,2)])<br>...     route_example.duration = 123<br><strong>... except </strong>Exception <strong>as </strong>e:<br>...     print(e)<br>...<br>&#39;route&#39; object has no attribute &#39;duration&#39;</pre><p>Another option is to provide a definition for <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__slots__#object.__setattr__">__setattr__</a> that raises an exception, ensuring that it is not possible to add new attributes or to assign new values to an existing attribute.</p><h3>Further Reading</h3><p>This article provides an overview of the distinction between mutable and immutable data structures in Python, why the distinction exists, and guidance on what options are available to a programmer when they are implementing an application-specific immutable data structure. The information about the <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple">namedtuple</a> factory function in the built-in <a href="https://docs.python.org/3/library/collections.html">collections</a> library may be relevant to some scenarios. The third-party <a href="https://pypi.org/project/attrs/">attrs</a> library can help reduce the amount of boilerplate required to define new classes (even if you are not relying on inheritance) and has features that help introduce <a href="https://www.attrs.org/en/stable/api.html#attr.attr.frozen">immutability</a>. To learn more about the nuances of object and memory management within the Python interpreter, you can read about <a href="https://docs.python.org/3/library/sys.html#sys.intern">interning</a>. Those more familiar with C may find it useful to explore the <a href="https://docs.python.org/3/c-api/memory.html">Memory Management</a> documentation (targeting primarily at readers who are interested in implementing their own extensions to the Python interpreter).</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/applications-of-immutability/blob/master/applications-of-immutability.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/applications-of-immutability"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2580266ef57b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/applications-of-immutability-2580266ef57b">Applications of Immutability</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Foreign Functions]]></title>
            <link>https://medium.com/python-supply/working-with-foreign-functions-ee3b5e40f2ca?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/ee3b5e40f2ca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 06:02:34 GMT</pubDate>
            <atom:updated>2021-04-25T21:58:34.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwZWLFtKqm_PrAGU_nB50g.png" /></figure><p>Suppose your Python library needs to load some sensitive binary data from a file into a contiguous block of memory (<em>e.g.</em>, in order to use it for some application-specific operation). Furthermore, you have some additional requirements that must be met for security and auditing purposes:</p><ul><li>you need to ensure that your code does not inadvertently cause the interpreter to copy any part of the data loaded from the file into some other region of memory,</li><li>you need to log the memory address at which the data was stored, and</li><li>you need to clear the memory region that held the data by overwriting it with random bytes.</li></ul><p>One strategy you might employ in order maintain tight control over what your code is doing is to use C functions found in a compiled shared library to read the data from disk, to load that data into a region of memory, and at the end to clear that region. What minimal collection of built-in Python features will you need to invoke functions that are found in a shared library? How can you transform Python values (such as strings representing the location of the file) into an appropriate form on which the function can operate?</p><p>Python offers a rich set of capabilities via the built-in <a href="https://docs.python.org/3/library/ctypes.html">ctypes</a> library that make it possible to invoke (or wrap in a Python function) foreign functions that have been implemented using another language (such as C/C++) and compiled into shared libraries. This article reviews the basics of employing foreign functions by demonstrating how to load and apply to the above use case the instance of the <a href="https://www.gnu.org/software/libc/">GNU C Library</a> available on most operating systems. The same techniques can be used for any shared library. An alternative approach used by some popular Python packages is briefly reviewed, as well.</p><h3>Loading a Shared Library</h3><p>To load a shared library file for which you know the relative or absolute path, you can normally use the <a href="https://docs.python.org/3/library/ctypes.html#loading-dynamic-link-libraries">LoadLibrary</a> method of either the cdll or the windll instance (depending on your operating system) of the <a href="https://docs.python.org/3/library/ctypes.html#ctypes.LibraryLoader">LibraryLoader</a> class found in <a href="https://docs.python.org/3/library/ctypes.html">ctypes</a>. For the purposes of the use case in this article, it is sufficient to load the GNU C Library. In the example below, the <a href="https://docs.python.org/3/library/platform.html#platform.system">system</a> function from the <a href="https://docs.python.org/3/library/platform.html">platform</a> library is used to distinguish between Windows and Linux/macOS environments. In the Linux/macOS case, the <a href="https://docs.python.org/3/library/ctypes.html#finding-shared-libraries">find_library</a> function is used to determine the absolute path of the shared library.</p><pre><strong>import </strong>ctypes<br><strong>import </strong>platform</pre><pre><strong>if </strong>platform.system() == &quot;Windows&quot;:<br>    libc = ctypes.windll.msvcrt<br><strong>else</strong>:<br>    libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library(&quot;c&quot;))</pre><h3>Invoking Foreign Functions</h3><p>The first portion of your workflow involves loading a file into memory. The Python code below writes a file to disk that contains a sequence of 32 random bytes. The file can be used to test the workflow.</p><pre><strong>from </strong>secrets <strong>import </strong>token_bytes<br><strong>with </strong>open(&quot;data.txt&quot;, &quot;wb&quot;) <strong>as </strong>file:<br>    file.write(token_bytes(32))</pre><p>The C function <a href="https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html">fopen</a> expects two arguments: a pointer to the first character of a string that represents the path of the file, and a pointer to the first character of the string that represents the mode (<em>i.e.</em>, reading or writing) in which the file is opened. You can use the <a href="https://docs.python.org/3/library/ctypes.html#ctypes.c_char_p">c_char_p</a> function to turn Python strings into a representation in memory that can be handled by the C function. Note the use of the <a href="https://docs.python.org/3/library/stdtypes.html#str.encode">encode</a> string method to provide an explicit encoding for the string as a byte sequence.</p><pre><strong>from </strong>ctypes <strong>import </strong>c_char_p<br>file = c_char_p(&quot;data.txt&quot;.encode(&quot;ascii&quot;))<br>mode = c_char_p(&quot;rb&quot;.encode(&quot;ascii&quot;))</pre><p>Unfortunately, it is not possible within Python to examine the libc object that was created by the <a href="https://docs.python.org/3/library/ctypes.html#ctypes.LibraryLoader">LibraryLoader</a> instance in order to determine what symbols are defined within it. However, in this case we know that the functions fopen, fread, and fclose must exist. For each of these functions, an instance of the <a href="https://docs.python.org/3/library/ctypes.html#ctypes._FuncPtr">FuncPtr</a> class can be found in libc.</p><pre>fopen = libc.fopen<br>fread = libc.fread<br>fclose = libc.fclose</pre><p>Before you can safely invoke these functions, you need to <a href="https://docs.python.org/3/library/ctypes.html#specifying-the-required-argument-types-function-prototypes">specify their argument types</a> and their <a href="https://docs.python.org/3/library/ctypes.html#return-types">return types</a>. This can be accomplished by first consulting the <a href="https://www.gnu.org/software/libc/">GNU C Library</a> documentation to find the signature for each of the C functions you would like to use. Then, the appropriate <a href="https://docs.python.org/3/library/ctypes.html#fundamental-data-types">data type classes</a> can be used to assign the correct sequence of argument types and the correct return type to the argtypes and restype attributes, respectively, of each FuncPtr class instance.</p><pre><strong>from </strong>ctypes <strong>import </strong>c_int, c_size_t, c_void_p</pre><pre>fopen.argtypes = [c_char_p, c_char_p]<br>fopen.restype = c_void_p</pre><pre>fread.argtypes = [c_void_p, c_size_t, c_size_t, c_void_p]<br>fread.restype = c_size_t</pre><pre>fclose.argtypes = [c_void_p]<br>fclose.restype = c_int</pre><p>It is now possible to invoke these functions on some inputs. You can allocate a memory buffer for the 32 bytes of data that you will be loading from the file using the <a href="https://docs.python.org/3/library/ctypes.html#ctypes.create_string_buffer">create_string_buffer</a> function.</p><pre><strong>from </strong>ctypes <strong>import </strong>create_string_buffer<br>data = ctypes.create_string_buffer(32)</pre><p>You can now open the file, load the data, and close the file.</p><pre>&gt;&gt;&gt; fp = fopen(file, mode)<br>&gt;&gt;&gt; fread(data, 32, 1, fp)<br>&gt;&gt;&gt; fclose(fp)<br>&gt;&gt;&gt; bytes(data).hex()<br>&#39;6d1481fda1e3853c14d81c6f1c4f87fcf26aca8f8d628d2cc31067781f9624ce&#39;</pre><p>You can determine the memory address corresponding to the memory buffer data using the <a href="https://docs.python.org/3/library/ctypes.html#ctypes.addressof">addressof</a> function.</p><pre>&gt;&gt;&gt; <strong>from</strong> ctypes <strong>import </strong>addressof<br>&gt;&gt;&gt; hex(addressof(data))<br>&#39;0xd788e0&#39;</pre><p>You can now clear the memory region. The example below uses the memset C function for this purpose. An example that uses a random sequence generator that is appropriate for cryptographic applications appears in the next section.</p><pre>&gt;&gt;&gt; libc.memset.argtypes = [c_void_p, c_int, c_size_t]<br>&gt;&gt;&gt; libc.memset(data, 0, 32)<br>&gt;&gt;&gt; bytes(data).hex()<br>&#39;0000000000000000000000000000000000000000000000000000000000000000&#39;</pre><h3>Alternative Approaches</h3><p>The <a href="https://cffi.readthedocs.io/">C Foreign Function Interface</a> library is similar to the built-in ctypes module and is used by some popular packages, including the <a href="https://pypi.org/project/PyNaCl/">PyNaCl</a> library that acts as a Python interface for the cryptographic library <a href="https://doc.libsodium.org/">libsodium</a>. In the example below, the C implementation of the <a href="https://libsodium.gitbook.io/doc/generating_random_data">randombytes</a> function is invoked on a character buffer bs and then the contents of that buffer are displayed.</p><pre><strong>&gt;&gt;&gt; from </strong>nacl <strong>import </strong>_sodium<br><strong>&gt;&gt;&gt; </strong>lib = _sodium.lib<br><strong>&gt;&gt;&gt;<br>&gt;&gt;&gt; from </strong>cffi <strong>import </strong>FFI<br><strong>&gt;&gt;&gt; </strong>ffi = FFI()<br><strong>&gt;&gt;&gt;<br>&gt;&gt;&gt; </strong>bs = ffi.new(&quot;unsigned char[]&quot;, 8)<br><strong>&gt;&gt;&gt; </strong>lib.randombytes(bs, 8)<br><strong>&gt;&gt;&gt; </strong>bytes(bs).hex()<br>&#39;a215d495f3e4248f&#39;</pre><p>You might choose to call the C implementation directly for a variety of reasons, including to improve performance. This may be useful to do when a more high-level library method allocates new memory for a byte sequence during every invocation, while your own solution can reuse the same memory over and over to store each new batch of bytes. In the example below, the time to invoke the C function over one million iterations is measured.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>import </strong>time<br><strong>&gt;&gt;&gt;</strong> start = time.perf_counter()<br><strong>&gt;&gt;&gt;</strong> <strong>for </strong>_ <strong>in </strong>range(10**6):<br><strong>...</strong>     lib.randombytes(bs, 8)<br><strong>...</strong><br><strong>&gt;&gt;&gt;</strong> time.perf_counter() - start<br>2.583150100079365</pre><p>The below example measures the amount of time it takes to invoke the Python wrapper in PyNaCl over the same number of iterations. The longer running time may be the result of a number of factors; regardless of the underlying reason that may apply for any particular function, the example demonstrates that direct access to the C method gives you more control over those factors.</p><pre><strong>&gt;&gt;&gt;</strong> <strong>from</strong> nacl.bindings <strong>import </strong>randombytes<br><strong>&gt;&gt;&gt; </strong>start = time.perf_counter()<br><strong>&gt;&gt;&gt; for </strong>_ <strong>in </strong>range(10**6):<br><strong>...</strong>     bs = randombytes(8)<br><strong>...</strong><br><strong>&gt;&gt;&gt;</strong> time.perf_counter() - start<br>5.637964699999429</pre><h3>Further Reading</h3><p>If you are interested in learning what other C functions can be used in the manner described in this article, you can review <a href="https://www.gnu.org/software/libc/manual/html_node/index.html">The GNU C Library Reference Manual</a>. In addition to <a href="https://docs.python.org/3/library/ctypes.html">ctypes</a> and <a href="https://eli/cffi.readthedocs.io/">CFFI</a>, there exist specialized variants such as the <a href="https://numpy.org/">NumPy</a>-specific <a href="https://numpy.org/doc/stable/reference/routines.ctypeslib.html">numpy.ctypeslib</a> library (which comes with features that make it easier to package and deliver NumPy data structures to C functions). It is also possible to implement extension modules for Python in C/C++. Useful <a href="https://docs.python.org/3/extending/extending.html">definitions and guidelines</a> are provided that make it possible to write C/C++ code that interacts in appropriate ways with the Python interpreter. If you would like to leverage even more interoperation between Python and C/C++ code, you can investigate the <a href="https://cython.org/">Cython</a> compiler.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/working-with-foreign-functions/blob/master/working-with-foreign-functions.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/working-with-foreign-functions"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee3b5e40f2ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/working-with-foreign-functions-ee3b5e40f2ca">Working with Foreign Functions</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensions and Combinations]]></title>
            <link>https://medium.com/python-supply/comprehensions-and-combinations-664f1c178c24?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/664f1c178c24</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 06:45:33 GMT</pubDate>
            <atom:updated>2021-04-29T07:12:52.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FlTMgsgoSwq4A3S4CjBfQ.png" /></figure><p>If you are working on a project in which you must enumerate, traverse, and/or test every possible combination of elements from one or more finite (or even infinite) collections, Python provides a variety of ways to do so. This article reviews some of the <em>syntactically concise</em> ways to do so, while also addressing some relevant memory utilization aspects. In particular, the focus is on comprehension syntax as foundational building block that can be employed in conjunction with functions and recursion.</p><h3>Conventions for Terminology and Notation</h3><p>In order to maintain consistency across examples and to keep outputs deterministic, this articles follows the conventions enumerated below.</p><ul><li>Python lists are used to represent both collections that may have duplicates and sets that do not have duplicates. For example, the set {0, 1, 2} is represented using [0, 1, 2].</li><li>When including multiple collections (<em>e.g.</em>, <em>U</em>, <em>V</em>, and <em>W</em>) within a Cartesian product expression (<em>e.g.</em>, <em>U </em>× <em>V </em>× <em>W</em>), the collections are called <em>components</em> of the Cartesian product.</li><li>When an output evaluates to an iterable, it is sometimes immediately consumed and turned into a list using the list function so that it can be reused throughout an example multiple times. In practice, this may not be necessary and may even be unnecessarily expensive in terms of both memory utilization and running time. This distinction is noted explicitly where applicable.</li><li>A single-letter variable x usually refers to individual elements in a collection, a variable such as xs usually refers to collections of elements, and a variables such as xss usually refers to a collection of collections.</li></ul><h3>Cartesian Products</h3><p>One of the simplest scenarios is one in which it is necessary to generate every combination of elements from two or more collections, where each combination has one component from each collection. This corresponds to the <a href="https://en.wikipedia.org/wiki/Cartesian_product">Cartesian product</a> of the collections. Python’s <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">comprehension syntax</a> is a powerful language feature that, under the right circumstances, provides a way to implement such operations involving collections in a way that is concise and closely resembles widely used and recognized forms of mathematical notation. The example below demonstrates how this syntax can be used to build a Cartesian product of two lists.</p><pre><strong>&gt;&gt;&gt;</strong> [(x, y) <strong>for</strong> x <strong>in</strong> [0, 1, 2] <strong>for</strong> y <strong>in</strong> [&quot;a&quot;, &quot;b&quot;]]<br>[(0, &#39;a&#39;), (0, &#39;b&#39;), (1, &#39;a&#39;), (1, &#39;b&#39;), (2, &#39;a&#39;), (2, &#39;b&#39;)]</pre><p>Comprehension syntax can become difficult to manage and read as the number of component collections involved increases. In such cases, it may make sense to build a function so that the repetitive aspects of building the definition are handled programmatically. It is demonstrated at the end of this section how such a function can be defined. But first, some examples of how it can be used are illustrated using the product function found in the built-in <a href="https://docs.python.org/3/library/itertools.html">itertools</a> library.</p><pre><strong>&gt;&gt;&gt; from</strong> itertools <strong>import</strong> product<br><strong>&gt;&gt;&gt; </strong>u = [0, 1, 2]<br><strong>&gt;&gt;&gt; </strong>v = [&quot;a&quot;, &quot;b&quot;]<br><strong>&gt;&gt;&gt; </strong>list(product(u, v)) <em># Wrapped in `list` for display purposes.</em><br>[(0, &#39;a&#39;), (0, &#39;b&#39;), (1, &#39;a&#39;), (1, &#39;b&#39;), (2, &#39;a&#39;), (2, &#39;b&#39;)]</pre><p>The product function takes any number of <a href="https://docs.python.org/3/glossary.html#term-iterable">iterable</a> arguments and creates an iterable result containing one <a href="https://docs.python.org/3/library/stdtypes.html#tuple">tuple</a> for every combination of elements from each of the arguments.</p><pre><strong>&gt;&gt;&gt; </strong>r = [<strong>False</strong>, <strong>True</strong>]<br><strong>&gt;&gt;&gt; </strong>s = [0, 1, 2]<br><strong>&gt;&gt;&gt; </strong>t = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br><strong>&gt;&gt;&gt; </strong>p = list(product(r, s, t))<br><strong>&gt;&gt;&gt; </strong>len(p) == 2*3*4 <strong>and</strong> len(p[0]) == 3<br><strong>True</strong></pre><p>Using the <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists">unpacking</a> operator in conjunction with the list repetition operator (also <a href="https://docs.python.org/3/library/itertools.html#itertools.repeat">available as a method</a>), it is possible to concisely describe a Cartesian product of any number of instances of a finite collection. In the example below, a ten-dimensional discrete finite space is created (where each dimension is [0, 1, 2]).</p><pre><strong>&gt;&gt;&gt; </strong>s = [0, 1, 2]<br><strong>&gt;&gt;&gt; </strong>p = list(product(*[s]*10))<br><strong>&gt;&gt;&gt; </strong>len(p) == 3**10<br><strong>True</strong></pre><p>How much memory does an output of product consume? Because it is an iterable that generates data dynamically, it only takes about as much memory as the component collections provided as inputs to product.</p><pre><strong>&gt;&gt;&gt; import</strong> sys<br><strong>&gt;&gt;&gt; </strong>s = [0, 1, 2, 3, 4, 5, 6, 7]<br><strong>&gt;&gt;&gt; </strong>n = 10<br><strong>&gt;&gt;&gt; </strong>p = product(*[s]*n)<br><strong>&gt;&gt;&gt; </strong>(sys.getsizeof([s]*n), sys.getsizeof(p))<br>(68, 72)</pre><p>Now that it has been demonstrated how the function can be used, consider a recursive implementation of such a function. To understand how this can be accomplished, a concrete example may help. Suppose a Cartesian product p of two collections [False, True] and [0, 1] has already been built. How do you turn it into a Cartesian product of three collections? You can iterate over all combinations of elements from the third collection [&quot;a&quot;, &quot;b&quot;] and from the Cartesian product p, concatenating each element-combination pair.</p><pre><strong>&gt;&gt;&gt;</strong> p = [(x, y) <strong>for</strong> x <strong>in</strong> [<strong>False, True</strong>] <strong>for</strong> y <strong>in</strong> [0, 1]]<br><strong>&gt;&gt;&gt; </strong>q = [(z,) + t <strong>for</strong> z <strong>in</strong> [&quot;a&quot;, &quot;b&quot;] <strong>for</strong> t <strong>in</strong> p]<br><strong>&gt;&gt;&gt; </strong>q<br>[(&#39;a&#39;, <strong>False</strong>, 0),<br> (&#39;a&#39;, <strong>False</strong>, 1),<br> (&#39;a&#39;, <strong>True</strong>, 0),<br> (&#39;a&#39;, <strong>True</strong>, 1),<br> (&#39;b&#39;, <strong>False</strong>, 0),<br> (&#39;b&#39;, <strong>False</strong>, 1),<br> (&#39;b&#39;, <strong>True</strong>, 0),<br> (&#39;b&#39;, <strong>True</strong>, 1)]</pre><p>Below is a complete implementation of the function based on the above approach. Note that the base case is a collection containing a single tuple of length zero. The recursive case consists of a comprehension that prepends every element in the first collection to every tuple in the cartesian product of all the remaining collections.</p><pre><strong>def</strong> cart(xss):<br>    <strong>if</strong> len(xss) == 0:<br>        <strong>return </strong>[()]<br>    <strong>else</strong>:<br>        <strong>return </strong>[(x,) + ys <strong>for</strong> x <strong>in</strong> xss[0] <strong>for</strong> ys <strong>in</strong> cart(xss[1:])]</pre><p>You can confirm that cart produces the same output as product. However, note that its result is generated in its entirety when the function is called.</p><pre><strong>&gt;&gt;&gt;</strong> c = cart([range(0, 100), range(0, 100)])<br><strong>&gt;&gt;&gt; </strong>p = product(*[range(0, 100), range(0, 100)])<br><strong>&gt;&gt;&gt; </strong>set(c) == set(p)<br><strong>True<br>&gt;&gt;&gt;</strong> sys.getsizeof(c), sys.getsizeof(p)<br>43808 40</pre><p>A variant of this function that uses memory more efficiently can be created by turning the original definition into a <a href="https://wiki.python.org/moin/Generators">generator</a>. One added benefit of this approach is that the component collections can now be generators themselves (and, thus, can potentially <a href="https://medium.com/python-supply/iterators-generators-and-uncertainty-a3e7f85183b">contain an unknown number or even infinitely many elements</a>).</p><pre><strong>def </strong>cart(xss):<br>    <strong>if </strong>len(xss) == 0:<br>        <strong>yield </strong>()<br>    <strong>else</strong>:<br>        <strong>for</strong> t <strong>in </strong>((x,)+ys <strong>for</strong> x <strong>in </strong>xss[0] <strong>for</strong> ys <strong>in </strong>cart(xss[1:])):<br>            <strong>yield </strong>t</pre><p>The generator variant of cart function is nearly identical to product; the only difference is the absence of argument unpacking.</p><pre><strong>&gt;&gt;&gt;</strong> list(cart([[0, 1, 2], [&quot;a&quot;, &quot;b&quot;]]))<br>[(0, &#39;a&#39;), (0, &#39;b&#39;), (1, &#39;a&#39;), (1, &#39;b&#39;), (2, &#39;a&#39;), (2, &#39;b&#39;)]</pre><p>Because this function is a generator, it consumes approximately as much memory as is needed to keep track of the two component collections.</p><pre><strong>&gt;&gt;&gt;</strong> c = cart([range(0, 1000), range(0, 1000)])<br><strong>&gt;&gt;&gt; </strong>2 * sys.getsizeof(range(0, 1000))<br>48<br><strong>&gt;&gt;&gt;</strong> sys.getsizeof(c)<br>56</pre><h3>Power Sets</h3><p>A closely related scenario is one in which it may be necessary to generate every <em>subset</em> of a finite set (also known as the <a href="https://en.wikipedia.org/wiki/Power_set"><em>power set</em></a>). There are a number of approaches to building a power set. It is possible to use the Cartesian product as a building block by noting that every element in a set s of size len(s) is either <em>absent</em> (corresponding to False) or <em>present</em> (corresponding to True). Thus, you can first build a Cartesian product of len(s) instances of the set {False, True}.</p><pre><strong>&gt;&gt;&gt;</strong> s = {0, 1, 2}<br><strong>&gt;&gt;&gt;</strong> p = list(product(*[[<strong>False</strong>, <strong>True</strong>]]*len(s)))<br><strong>&gt;&gt;&gt;</strong> p<br>[(False, False, False),<br> (False, False, True),<br> (False, True, False),<br> (False, True, True),<br> (True, False, False),<br> (True, False, True),<br> (True, True, False),<br> (True, True, True)]</pre><p>It is then possible to use the built-in <a href="https://docs.python.org/3/library/functions.html#zip">zip</a> function and a comprehension (which employs an if clause for filtering) to associate the boolean values that make up each of the tuples in the Cartesian product with the corresponding elements in the original set.</p><pre><strong>&gt;&gt;&gt;</strong> ss = [{x <strong>for</strong> (b, x) <strong>in</strong> zip(bs, s) <strong>if</strong> b} <strong>for</strong> bs <strong>in</strong> p]<br><strong>&gt;&gt;&gt;</strong> len(ss) == 2**len(s)<br><strong>True</strong><br><strong>&gt;&gt;&gt;</strong> ss<br>[set(), {2}, {1}, {1, 2}, {0}, {0, 2}, {0, 1}, {0, 1, 2}]</pre><p>Alternatively, the Python documentation provides a <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes">recipe</a> for building power sets using the built-in itertools library.</p><pre><strong>from</strong> itertools <strong>import</strong> chain, combinations<br><strong>def</strong> powerset(iterable):<br>    s = list(iterable)<br>    <strong>return</strong> chain.from_iterable(<br>        combinations(s, r) <strong>for</strong> r <strong>in</strong> range(len(s) + 1)<br>    )</pre><p>The above variant yields a collection of tuples rather than sets, but otherwise produces the same collection of combinations.</p><pre><strong>&gt;&gt;&gt;</strong> list(powerset([0, 1, 2]))<br>[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]</pre><p>The recursive definition below employs an approach that is nearly identical to that of the recursive definition of the Cartesian production function. In the recursive case, every subset of all the remaining elements (excluding the current first element) is included in the overall result. However, a <em>second</em> copy of each of these subsets is taken and then paired (as in the Cartesian product function) with the current first element. This accounts for all subsets that <em>do include</em> the first element and all subsets that <em>do not include</em> it.</p><pre><strong>def</strong> powerset(xs):<br>    <strong>if </strong>len(xs) == 0:<br>        <strong>return </strong>[tuple()]<br>    <strong>else</strong>:<br>        x = xs[0]<br>        yss = powerset(xs[1:])<br>        <strong>return </strong>yss + [(x,) + ys <strong>for </strong>ys <strong>in </strong>yss]</pre><p>This approach yields the same results as the definition in the recipe, though it is worth noting that the exact implementation above leads to a different order. This distinction may be important in some applications (such as when performing a search for the largest subset that satisfies some criteria).</p><pre><strong>&gt;&gt;&gt;</strong> powerset([0, 1, 2])<br>[(), (2,), (1,), (1, 2), (0,), (0, 2), (0, 1), (0, 1, 2)]</pre><p>Can you apply the same technique used in the implementations of the cart function to turn the above recursive definition of powerset into a generator?</p><h3>Further Reading</h3><p>This article reviews how comprehensions, in concert with other built-in functions and Python features, can be used to assemble concise implementations of algorithms for generating common kinds of combinations of items from a collection. Many variants and relevant peripheral techniques can be found in a list of <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes">recipes</a> found in the documentation for the built-in <a href="https://docs.python.org/3/library/itertools.html">itertools</a> library. This includes functions such as <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations">combinations</a>, which can be used to obtain all subsets of a specific size. Other common set operations such as union and intersection are available as methods of the <a href="https://docs.python.org/3/library/stdtypes.html#set">built-in </a><a href="https://docs.python.org/3/library/stdtypes.html#set">set type</a>, and the built-in <a href="https://docs.python.org/3/library/collections.html">collections</a> library provides a variety of operations on collections (such as a class <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter</a> for concisely implementing counting workflows). Popular third-party libraries such as <a href="https://docs.scipy.org/">SciPy</a> contain <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.misc.comb.html#scipy.misc.comb">specialized functions</a> for common operations in combinatorics.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/comprehensions-and-combinations/blob/master/comprehensions-and-combinations.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/comprehensions-and-combinations"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664f1c178c24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/comprehensions-and-combinations-664f1c178c24">Comprehensions and Combinations</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Publishing Packages]]></title>
            <link>https://medium.com/python-supply/guide-to-publishing-packages-109dbbf41a77?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/109dbbf41a77</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-distribution]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 04:09:16 GMT</pubDate>
            <atom:updated>2021-05-24T04:59:41.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDk0pzCUmWYmZrYFsqqQbw.png" /></figure><p>This article is a step-by-step guide to assembling and publishing a small, open-source Python package. While not all of the steps below will be appropriate or desirable for every package, each of these can contribute to the accessibility and maintainability of the package. Note that this material is meant to serve as a roadmap and overview; it is not a thorough review of all the nuances and trade-offs involved. You are encouraged to consult additional resources (links are included throughout the text) for other options and viewpoints on how to approach every portion of the process.</p><p>Each section covers a task or category of tasks related to organizing and publishing a package and, where appropriate, provides templates and examples. Note that depending on when you are reading this article, some of the steps, templates, and examples may be out of date.</p><h3>Project Organization and Directory Tree Template</h3><p>The directory structure below is one way in which a hypothetical project called <strong>published</strong> might be organized.</p><pre>├─ .gitignore ............. File name patterns for Git to ignore <br>├─ .travis.yml ............ Travis CI configuration<br>│<br>├─ LICENSE ................ Distribution license<br>├─ README.rst ............. Project README<br>├─ setup.cfg .............. Configuration with parameters for setup<br>├─ setup.py ............... Package file<br>│<br>├─ published/<br>│  ├─ __init__.py ......... Namespace module<br>│  └─ published.py ........ Library module<br>│<br>└─ test/<br>   └─ test_published.py ... Unit tests</pre><p>For the purposes of this article, it is assumed that the package contains just one source module (<em>i.e.</em>, published/published.py). Therefore, it is sufficient to place it (along with its <a href="https://docs.python.org/3/tutorial/modules.html#packages">namespace module</a> published/__init__.py) into its own directory. The sections below go into more detail about each of the files and their purpose.</p><h3>Package File Organization</h3><p>The setup.py <a href="https://docs.python.org/3/distutils/apiref.html?highlight=setup%20py#distutils.core.setup">package file</a> specifies relevant metadata associated with your project, the locations of some important project files, and the dependencies that your project requires. An example of a possible setup.py file for the hypothetical package called <strong>published</strong> is presented below.</p><pre><strong>from</strong> setuptools <strong>import</strong> setup<br><br><strong>with</strong> open(&quot;README.rst&quot;, &quot;r&quot;) <strong>as</strong> fh:<br>    long_description = fh.read()<br><br>setup(<br>    name=&quot;published&quot;,<br>    version=&quot;0.1.0&quot;,<br>    packages=[&quot;published&quot;,],<br>    install_requires=[],<br>    license=&quot;MIT&quot;,<br>    url=&quot;https://pypi.org/project/published&quot;,<br>    author=&quot;python.supply&quot;,<br>    author_email=&quot;contact@python.supply&quot;,<br>    description=&quot;Example illustrating how an open-source library &quot;+\<br>                &quot;can be organized and published.&quot;,<br>    long_description=long_description,<br>    long_description_content_type=&quot;text/x-rst&quot;,<br>    test_suite=&quot;nose.collector&quot;,<br>    tests_require=[&quot;nose&quot;],<br>)</pre><h3>Establishing and Checking Style Conventions</h3><p>One easy way to add <a href="https://en.wikipedia.org/wiki/Lint_(software)">linting</a> to your project is to create a default configuration file for <a href="https://www.pylint.org/">Pylint</a>.</p><pre>python -m pip install pylint<br>pylint --generate-rcfile &gt; .pylintrc</pre><p>You can then check your project source files in the following way.</p><pre>pylint published</pre><p>In some cases, you may find it necessary to alter certain parameters in the configuration.</p><ul><li>The variable-rgx, class-rgx, constant-rgx, and similar parameters can be used to specify an alternate standard for acceptable naming conventions. This can be reasonable to do in certain scenarios. For example, if you are implementing a specialized library that involves certain mathematical constructs, it may be more clear to your audience and in accordance with domain conventions to use single-letter variables such as x and y rather than longer identifiers that use snake case.</li><li>You might add rules that you want to ignore to the comma-separated list that follows the disable= parameter.</li></ul><p>You may also want to direct Pylint to ignore a rule in a specific location within a source file. This can be done using a directive inside a comment. An example is presented below.</p><pre><strong>class</strong> published(): <em># pylint: disable=C0103,R0903</em><br>    <strong>def</strong> __init__(self):<br>        self.published = <strong>True</strong></pre><h3>Defining Unit Tests and Measuring Test Coverage</h3><p>There is an extensive supply of tools, packages, and conventions for defining unit tests, running unit tests, and measuring unit test coverage. In this article, the focus is on techniques that are suitable for small Python libraries and packages, so only two approaches are presented.</p><h4>Using doctest</h4><p>Unit tests for individual classes and methods can be included inside the <a href="https://www.python.org/dev/peps/pep-0257/">docstrings</a> that appear at the top of their bodies. The built-in <a href="https://docs.python.org/3/library/doctest.html">doctest</a> library can then be used to find and validate them. In the example below, the definition for the class published includes one such collection of tests in its docstring (<em>i.e.</em>, a sequence of executed statements and the corresponding results, as might be observed when engaging a session via the <a href="https://docs.python.org/3/tutorial/interpreter.html#interactive-mode">interactive prompt</a>).</p><pre><strong>class</strong> published():<br>    &quot;&quot;&quot;<br>    A published package.<br><br>    &gt;&gt;&gt; p = published()<br>    &gt;&gt;&gt; p.is_published()<br>    <strong>True</strong><br>    &gt;&gt;&gt; p.published = <strong>False</strong><br>    &gt;&gt;&gt; p.is_published()<br>    Traceback (most recent call last):<br>      ...<br>    RuntimeError: package must be published<br>    &quot;&quot;&quot;<br>    <strong>def</strong> __init__(self):<br>        &quot;&quot;&quot;Build an instance.&quot;&quot;&quot;<br>        self.published = <strong>True</strong><br><br>    <strong>def</strong> is_published(self):<br>        &quot;&quot;&quot;Check publication status.&quot;&quot;&quot;<br>        <strong>if</strong> <strong>not</strong> self.published:<br>            <strong>raise</strong> RuntimeError(&quot;package must be published&quot;)<br><br>        <strong>return</strong> self.published</pre><p>To check if the outputs in these sequences are accurate descriptions of what is actually returned by the Python interpreter when it runs each statement, simply add the following to your main module (<em>e.g.</em>, inside published.py in this case):</p><pre><strong>if</strong> __name__ == &quot;__main__&quot;:<br>    doctest.testmod()</pre><p>It is then possible to <a href="https://docs.python.org/3/library/__main__.html">run these tests</a> as follows (the -v option ensures a report is displayed even if all tests succeed):</p><pre>python published/published.py -v</pre><p>Alternatively, you can allow <a href="https://nose.readthedocs.io/en/latest/">nose</a> to find and run doctests using appropriate parameters in a <a href="https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html?highlight=setup.cfg">setup.cfg</a> file. An example of asetup.cfg file that is sufficient for the examples above is presented below.</p><pre>[nosetests]<br>exe=True<br>tests=published/published.py</pre><h4>Using unittest</h4><p>If you would like to employ a more extensive test suite, you can create one using the built-in <a href="https://docs.python.org/3/library/unittest.html">unittest</a> library and put it in a location that the <a href="https://nose.readthedocs.io/en/latest/">nose</a> tool can locate automatically. Below is an example of the layout a test script test/test_published.py might have.</p><pre><strong>from</strong> unittest <strong>import</strong> TestCase<br><strong>from</strong> published.published <strong>import</strong> published</pre><pre><strong>class</strong> Test_published(TestCase):<br>    <strong>def</strong> test_is_published(self):<br>        p = published()<br>        self.assertTrue(p.is_published())</pre><p>To ensure nose can find the test script, the setup.cfg configuration file should specify the directory that contains the test script.</p><pre>[nosetests]<br>exe=True<br>with-doctest=1<br>tests=test/</pre><h4>Using both doctest and unittest with nose</h4><p>It is possible to use nosetests to run all tests, including both doctest unit tests and any testing scripts. An example of a setup.cfg file that enables this is provided below.</p><pre>[nosetests]<br>exe=True<br>with-doctest=1<br>tests=published/published.py, test/</pre><h4>Measuring coverage</h4><p>To determine how much of your code is covered by unit tests every time you use nose, you can add a few optional lines to the setup.cfg file.</p><pre>[nosetests]<br>exe=True<br>with-doctest=1<br>cover-package=published<br>cover-html=1<br>tests=published/published.py, test/</pre><p>By assigning your package name to cover-package, you are indicating that coverage should be measured (typically using <a href="https://coverage.readthedocs.io/">coverage</a>). By assigning 1 to cover-html, you are indicating that human-readable HTML files should be generated that highlight what portions of the module files are not covered by any unit tests.</p><h3>Continuous Integration and Coverage Reporting</h3><p>You can connect your GitHub personal or organization account with <a href="https://travis-ci.org/">Travis CI</a> and <a href="https://coveralls.io/">Coveralls</a> in order to automatically run tests and publish test coverage every time you or a contributor pushes to the package’s GitHub repository or makes a pull request. Travis CI and Coveralls provide extensive documentation describing how you can link your GitHub account with their services; this article focuses is on what configuration files you need to add to your project.</p><p>A template for a simple .travis.yml <a href="https://config.travis-ci.com/">Travis CI configuration file</a> for the hypothetical package called <strong>published</strong> is provided below.</p><pre>notifications:<br>  email:<br>    on_success: never<br>    on_failure: always<br>language: python<br>python:<br>  - &quot;3.8&quot;<br>cache: pip<br>install:<br>  - pip install pylint<br>  - pip install coveralls<br>  - pip install .<br>script:<br>  - pylint published<br>  - nosetests<br>after_success:<br>  - coveralls</pre><p>The notifications section indicates that email notifications should only be sent if any step in the script section produces any result other than 0 (usually indicating success) to the standard output. The pylint and nosetests commands conform to this convention. The after_success section includes an entry that publishes the coverage results via Coveralls if there are no linting issues and no errors arise when the unit tests are executed.</p><h3>README Organization and Format</h3><p>An effective README document might cover some of the following topics:</p><ul><li>the purpose of the package/libary;</li><li>a quick start guide showing how a first-time user can begin using the package/library;</li><li>how to run unit tests and measure test coverage;</li><li>how others can contribute;</li><li>the versioning standards or conventions being used.</li></ul><p>Two popular formats for a README file that are supported by GitHub and PyPI are <a href="https://daringfireball.net/projects/markdown/">Markdown</a> and <a href="https://docutils.sourceforge.io/rst.html">reStructuredText</a>. You can also learn more about <a href="https://packaging.python.org/guides/making-a-pypi-friendly-readme/">how to structure a README file for PyPI</a>.</p><h4>Badges</h4><p>You may want to add badges to your README that provide information about the status of your project (<em>e.g.</em>, the host package repository and version number of the latest release, the last Travis CI build outcome, test coverage statistics, and so on). This requires determining the image URL for the badge you want to display (for example, the <a href="https://docs.travis-ci.com/user/status-images/">badge image URL for last Travis CI build status</a> for the hypothetical package called <strong>published</strong> might be https://travis-ci.com/python-supply/published.svg) and then inserting that image into your README document using the appropriate syntax. For example, when using the reStructuredText format, the badge section of the README.rst file for the package <strong>published</strong> might look as follows if it uses a <a href="https://docutils.sourceforge.io/0.4/docs/ref/rst/directives.html#directives-for-substitution-definitions">substitution definition</a> for an <a href="https://docutils.sourceforge.io/0.4/docs/ref/rst/directives.html#image">images</a> in order to include a badge for PyPI.</p><pre>|pypi|</pre><pre>.. |pypi| image:: <a href="https://badge.fury.io/py/published.svg">https://badge.fury.io/py/published.svg</a><br>   :target: <a href="https://badge.fury.io/py/published">https://badge.fury.io/py/published</a></pre><h4>Versioning and Contributions</h4><p>When deciding how to assign version numbers to different versions or releases of your package, there are advantages to adopting a published standard. An example of a popular standard is <a href="https://semver.org/#semantic-versioning-200">Semantic Versioning 2.0.0</a>. One benefit of a standard is that it makes it easier for anyone working with your package to understand what the difference between two versions signifies (<em>e.g.</em>, whether they can expect one version to be backwards compatible with another). Another benefit is that it reduces the burden on you as the author and maintainer, as you do not need to invest effort in documenting your own conventions and resolving any corner cases that might arise. Of course, this may come at some cost or additional effort if your goal is to adhere to the standard consistently.</p><p>You may also want to specify in the README document any expectations you have of contributors who may be interested in reporting issues or making improvements to your package. For example, you might direct potential contributors to report problems via <a href="https://guides.github.com/features/issues/">GitHub Issues</a> and to submit suggested fixes or enhancements via <a href="https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/about-pull-requests">pull requests</a>.</p><h3>Publishing to PyPI</h3><p>Once you are ready to publish your package, you may want to test one last time that the package file and other project files are organized appropriately by installing the package locally.</p><pre>python -m pip install .</pre><p>You can then generate the archive files for distribution.</p><pre>python setup.py sdist bdist_wheel</pre><p>These can then be contributed to <a href="https://pypi.org/">PyPI</a> after you have set up an account. When you run the command below for the first time, you will be asked for your PyPI credentials.</p><pre>twine upload dist/*</pre><p>You can then try installing your package from PyPI. The example below is for the hypothetical package called <strong>published</strong>.</p><pre>python -m pip install published</pre><p>If you already installed a version locally, you may want to ensure you upgrade to the latest version using the --upgrade and --force-reinstall options.</p><pre>python -m pip install --upgrade --force-reinstall published</pre><h3>Further Reading</h3><p>This guide provides templates and examples that are just one path, involving a minimal number of steps, to organizing and publishing a small package. Not all of these steps may be appropriate for your particular package, and there are many variations and extensions of what is presented here. For a more detailed guide to packaging and publishing, you might want to refer to the <a href="https://packaging.python.org/">Python Packaging User Guide</a> and the <a href="https://setuptools.readthedocs.io/en/latest/">Setuptools documentation</a>. You may also want to explore alternatives that may exist for every step in this guide:</p><ul><li>other frameworks for unit testing (<em>e.g.</em>, <a href="https://behave.readthedocs.io/en/latest/">behave</a>), linting (<em>e.g.</em>, <a href="https://pycodestyle.pycqa.org/en/latest/">pycodestyle</a>), and static analysis (<em>e.g.</em>, <a href="http://mypy-lang.org/">mypy</a>);</li><li>other CI/CD workflow options such as <a href="https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/">GitHub Actions</a>; and</li><li>other <a href="https://packaging.python.org/guides/tool-recommendations/">packaging tools and frameworks</a>,</li></ul><p>When evaluating alternatives, it is a good idea to check the level of activity in the community surrounding them, in addition to their suitability for your particular package. The long-term maintainability and compatibility of your package may be impacted if the tools and frameworks on which it relies are not well-supported or are phased out.</p><p><em>This article is also available in </em><a href="https://github.com/python-supply/guide-to-publishing-packages"><em>Markdown form</em></a><em> on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>. The hypothetical package called </em><strong><em>published</em></strong><em> used as an example throughout the article is actually not so hypothetical and can be found on </em><a href="https://github.com/python-supply/published"><em>GitHub</em></a><em> and </em><a href="https://pypi.org/project/published/"><em>PyPI</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109dbbf41a77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/guide-to-publishing-packages-109dbbf41a77">Guide to Publishing Packages</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static Checking via Metaclasses]]></title>
            <link>https://medium.com/python-supply/static-checking-via-metaclasses-cec368765b58?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/cec368765b58</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 00:55:29 GMT</pubDate>
            <atom:updated>2020-10-28T18:49:57.618Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are maintaining a domain-specific machine learning library. Users of the library’s API expect that every machine learning algorithm offered by the API will have the same interface (<em>i.e.</em>, the same methods with the same signatures) regardless of its underlying implementation. You would like to allow a community of contributors to define new algorithms that can be added to the library, but you would like to reduce your own effort and that of contributors when it comes to validating that a new algorithm conforms to the API.</p><p>Python <a href="https://docs.python.org/3/reference/datamodel.html#metaclasses">metaclasses</a> are the underlying, higher-order constructs that instantiate class definitions. Understanding what metaclasses are and how they can be used gives you a significant amount of control over what happens when a new class is introduced by users. This in turn allows you to constrain users when necessary <em>and</em> to provide assistance to users that can save them time and effort.</p><h3>How Classes are Made</h3><p>In Python, functions, classes, objects, and values are all on an equal footing. One consequence of this is that it is possible to pass any of these entities as arguments to functions and to return any of these entities as the result of a function (this fact was discussed in <a href="https://medium.com/python-supply/higher-order-functions-and-decorators-d6bb31a5c78d">another article</a> that covered Python decorators). But this also means that much of the syntax you normally use is actually just syntactic sugar for function calls.</p><p>What happens when the Python interpreter executes a class definition such as the one below?</p><pre><strong>class</strong> Document():<br>    <strong>def</strong> __init__(self):<br>        self.is_document = <strong>True</strong></pre><p>The <em>class</em> (<em>not</em> an instance or object of that class, but <em>the class itself</em>) is created and assigned to a variable that is in scope. In the example above, that variable is Document.</p><pre>&gt;&gt;&gt; Document<br>__main__.Document</pre><p>Python’s built-in <a href="https://docs.python.org/3/library/functions.html#type">type</a> function actually serves a number of purposes beyond determining the type of a value. Given a few additional parameters, the type function can be used to <em>define a new class</em>. Executing the statement in the example below is equivalent to executing the class definition for Document above.</p><pre><strong>def</strong> __init__(self):<br>    self.is_document = <strong>True<br><br></strong>Document = type(&#39;Document&#39;, (), {&#39;__init__&#39;: __init__})</pre><p>Now that Document is a class, it is possible to create objects of this class.</p><pre>&gt;&gt;&gt; d = Document()<br>&gt;&gt;&gt; d.is_document<br><strong>True</strong></pre><h3>How Metaclasses are Made</h3><p>In a manner similar to that of many programmaing languages that support the <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a> paradigm, Python allows programmers to define <em>derived</em> classes that <a href="https://docs.python.org/3/tutorial/classes.html#inheritance">inherit</a> the attributes and methods of a base class. The example below illustrates this by defining a class Passport that is derived from the Document class. Notice that the base class constructor Document is specified in the class definition.</p><pre><strong>class</strong> Passport(Document):<br>    <strong>pass</strong></pre><p>The Passport class inherits the attributes of the Document class. The example below illustrates that it inherits the __init__ method of the Document class.</p><pre>&gt;&gt;&gt; p = Passport()<br>&gt;&gt;&gt; p.is_document<br><strong>True</strong></pre><p>The example in which Document was defined using the built-in type function suggests that type can be viewed (at least using a loose analogy) as a means for creating classes. In a way, it behaves like a constructor for the &quot;class of all possible classes&quot;. Thus, if type is a kind of constructor for a class, it should be possible to use it in the same context as any other class constructor. But what should this mean? What is MetaClass in the example below?</p><pre><strong>class</strong> MetaClass(type):<br>    <strong>pass</strong></pre><p>Following the analogy to its logical conclusion, this must mean that MetaClass has inherited the capabilities of type. And, indeed, it has. In the example below, MetaClass is used to define a new class — in the same way that type was used before.</p><pre>&gt;&gt;&gt; Document = MetaClass(&#39;Document&#39;, (), {&#39;__init__&#39;: __init__})<br>&gt;&gt;&gt; d = Document()<br>&gt;&gt;&gt; d.is_document<br><strong>True</strong></pre><p>The ability to use a metaclass in place of type as in the above example is also supported by the more common class syntactic construct.</p><pre><strong>class</strong> Document(metaclass=MetaClass):<br>    <strong>def</strong> __init__(self):<br>        self.is_document = <strong>True</strong></pre><h3>Using Metaclasses to Enforce an API</h3><p>eturning to the motivating example from the first paragraph, suppose you introduce a metaclass called MetaAlgorithm for machine learning algorithms that is derived from type. This metaclass definition can override the method <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__new__#object.__new__">__new__</a> that is normally invoked when a new class is defined using type (or using the equivalent class syntactic construct). This alternate definition of __new__ performs some additional checks before the class is actually created. In this use case, that additional work involves validating that the class being defined (corresponding to a new machine learning algorithm) conforms to your API.</p><pre><strong>from </strong>types <strong>import</strong> FunctionType<br><br><strong>class</strong> MetaAlgorithm(type):<br>    <strong>def</strong> __new__(cls, clsname, bases, attrs):<br>        <br>        <em># The base class does not need to conform to the API.</em><br>        <em># See the paragraph below for an explanation of this check.</em><br>        <strong>if</strong> clsname != &#39;Algorithm&#39;:<br>            <br>            <em># Check that the programmer-defined</em><br>            <em># class has a contributor string.</em><br>            <strong>if</strong> &#39;contributor&#39; <strong>not</strong> <strong>in</strong> attrs <strong>or</strong>\<br>               <strong>not</strong> isinstance(attrs[&#39;contributor&#39;], str):<br>                <strong>raise</strong> RuntimeError(&#39;missing contributor&#39;)<br>            <br>            <em># Check that the programmer-defined class has the<br>            # methods required for your API.</em><br>            <strong>if</strong> &#39;train&#39; <strong>not in</strong> attrs <strong>or</strong>\<br>               <strong>not</strong> isinstance(attrs[&#39;train&#39;], FunctionType):<br>                raise RuntimeError(&#39;missing training method&#39;)<br>            <br>            <strong>if</strong> &#39;classify&#39; <strong>not in</strong> attrs <strong>or</strong>\<br>               <strong>not</strong> isinstance(attrs[&#39;classify&#39;], FunctionType):<br>                <strong>raise</strong> RuntimeError(&#39;missing training method&#39;)<br>        <br>        <strong>return</strong>\<br>            super(MetaAlgorithm, cls)\<br>            .__new__(cls, clsname, bases, attrs)</pre><p>Now that there is a way to define new classes, there are two ways to proceed. One approach is to require that all algorithm classes that contributors implement must include the metaclass=MetaAlgorithm parameter in the class definition. However, this is easy for a contributor to forget and also may require that contributors have a solid understanding of metaclasses. An alternative is to create a base class from which all contributed algorithm classes must be derived.</p><pre><strong>class</strong> Algorithm(metaclass=MetaAlgorithm):<br>    <strong>pass</strong></pre><p>Using this approach, it is sufficient to export the Algorithm base class and to inform all contributors that their classes must be derived from this base class. The example below illustrates how a contributor might do so for a very basic algorithm.</p><pre><strong>class</strong> Guess(Algorithm):<br>    contributor = &quot;Author&quot;<br>    <br>    <strong>def</strong> train(items, labels):<br>        <strong>pass<br>    <br>    def</strong> classify(item):<br>        <strong>import </strong>random<br>        <strong>return</strong> random.choice([<strong>True</strong>, <strong>False</strong>])</pre><p>As the example below illustrates, an attempt by a user to define a class that does not conform to the API results in an error.</p><pre>&gt;&gt;&gt; try:<br>...     <strong>class</strong> Guess(Algorithm):<br>...         <strong>def</strong> classify(item):<br>...             <strong>return False<br></strong>...<br>... <strong>except</strong> RuntimeError <strong>as</strong> error:<br>...     print(&quot;RuntimeError:&quot;, str(error))<br>...<br>RuntimeError: missing contributor</pre><p>To emphasize: the error above occurs when the Python interpreter tries to execute the <em>definition</em> of the class, and <em>not</em> when an object of the class is created. It would be impossible to reach the point at which the interpreter attempts to create an object of this class because the class itself can never be defined.</p><p>Despite the fact that Python does not technically support static checking beyond ensuring that the syntax of a module is correct, it is arguably justifiable to say that what MetaAlgorithm does is a form of static checking. In many routine scenarios, the checks would be performed at the time that module is imported and before any other code has had a chance to run.</p><h3>Further Reading</h3><p>This article reviewed how user-defined classes are created in Python and how the mechanism for introducing classes can itself be customized. The built-in <a href="https://docs.python.org/3/library/types.html#module-types">types</a> library provides a number of additional methods that can assist in the dynamic creation of new types and classes. The motivating example in this article illustrated how these capabilities can be used to perform a form of <a href="https://en.wikipedia.org/wiki/Static_program_analysis">static analysis</a> of user-defined classes.</p><p>It is worth noting that the approach presented in this article is compatible with the methods for checking type annotations and unit testing functions presented in the article on <a href="https://medium.com/python-supply/advantages-of-type-annotations-6c6eb70fa631">type annotations</a>. For example, it would be straightforward to require that the training and classification method definitions include annotations specifying the exact types of the data that they can handle. It would even be possible to test the methods by generating test cases having the appropriate types. Another observation is that the motivating use case in this article can also be solved by using techniques presented in other articles, such as by applying <a href="https://medium.com/python-supply/higher-order-functions-and-decorators-d6bb31a5c78d">decorators</a> to class definitions or by performing a <a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">static analysis</a> of the class definition itself.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/static-checking-via-metaclasses/blob/master/static-checking-via-metaclasses.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/static-checking-via-metaclasses"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec368765b58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/static-checking-via-metaclasses-cec368765b58">Static Checking via Metaclasses</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advantages of Type Annotations]]></title>
            <link>https://medium.com/python-supply/advantages-of-type-annotations-6c6eb70fa631?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/6c6eb70fa631</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Mon, 26 Oct 2020 00:32:48 GMT</pubDate>
            <atom:updated>2020-10-26T00:31:51.552Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are working on a project in Python that takes advantage of Python’s support for higher-order functions. Perhaps you are allowing users to specify their own hooks or event handlers within a <a href="https://flask.palletsprojects.com/">web application framework</a>, or you are creating a <a href="https://hypothesis.readthedocs.io/">unit testing library</a> that generates test cases for a user-supplied function. In many such use cases, you might find yourself dealing with two related scenarios:</p><ul><li>user-supplied functions can return results of different types and you do not know in advance what the result type of any given user-supplied function will be, or</li><li>your code needs to generate inputs to user-supplied functions that have the type the user-supplied function expects.</li></ul><p>The first of these cases is more straightforward to handle at runtime: inspect the type of the output and branch accordingly. However, in the event that you need to determine this information in advance, you may not always be free to invoke the function (<em>e.g.</em>, if the function relies on some resource that is <a href="https://medium.com/python-supply/iterators-generators-and-uncertainty-a3e7f85183b">not yet available</a> or running the function has a very high cost). The second is more evidently difficult, and you would need to provide for the user a way to specify the input type. How can you organize your API to handle both of these issues in a way that keeps your API clean and allows users of your API to leverage features already built into Python?</p><h3>Type Information and the Python Syntax</h3><p>While there exist within the Python community standards for documenting information about the inputs and outputs of functions and methods within <a href="https://www.python.org/dev/peps/pep-0257">docstrings</a> (such as <a href="https://google.github.io/styleguide/pyguide.html#383-functions-and-methods">those in the Google Python Style Guide</a>), it is explicitly recommended that the information inside docstrings <a href="https://www.python.org/dev/peps/pep-0257/#one-line-docstrings">should <em>not</em> consist of a signature</a>. This is in contrast with documentation conventions maintained by communities for other programming languages (such as <a href="https://jsdoc.app/tags-type.html">JSDoc</a>).</p><p>So how should programmers document the exact type signature of a function if they wish to do so? Starting with Python 3.5, the Python syntax was <a href="https://www.python.org/dev/peps/pep-0484/">extended</a> with mature and well-developed features that allow for <em>type annotations</em>: the ability to specify the types of variables and functions at the time they are defined. The <a href="https://docs.python.org/3/library/typing.html">documentation</a> calls these <em>type hints</em> because it is a purely syntactic feature. Type annotations are <em>not checked</em> statically (<em>i.e.</em>, at the time the code is parsed and transformed into bytecode) or dynamically (<em>i.e.</em>, when the code is actually running).</p><p>The cosmetic quality of this built-in feature does not limit its utility, however. In addition to providing a more standard and formally endorsed representation for information that might otherwise be relegated to documentation strings or formatted comments, the Python community is free to write its own static and dynamic analysis tools that use the native syntax for type annotations.</p><p>More information on the built-in type specification library and the type annotation concrete syntax can be found in its <a href="https://docs.python.org/3/library/typing.html">documentation page</a>. The corresponding new additions to the Python abstract syntax (a topic covered in more detail in <a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">another article</a>) are actually quite few in number. A comparison of the <a href="https://docs.python.org/2.7/library/ast.html#abstract-grammar">Python 2.7 grammar</a> and the <a href="https://docs.python.org/3.6/library/ast.html#abstract-grammar">Python 3.6 grammar</a> shows that new parameters appear in only a few places:</p><ul><li>function argument types are specified using the annotation parameter in the arg parameter of the FunctionDef and AsyncFunctionDef cases,</li><li>function output types are specified using the returns parameter in the FunctionDef and AsyncFunctionDef cases, and</li><li>the type of the variable being assigned is specified in the annotation parameter of the AnnAssign case.</li></ul><p>All that is really happening here is that the Python syntax now has a few extra contexts, delimited using the tokens : and -&gt;, in which programmers can add expressions that will make it into the abstract syntax tree as type annotations.</p><h3>Annotations with Built-in Types</h3><p>By convention, type annotations that refer to built-in types simply use the type constructors (<em>e.g.</em>, <a href="https://docs.python.org/3/library/functions.html#int">int</a>, <a href="https://docs.python.org/3/library/functions.html#float">float</a>, and <a href="https://docs.python.org/3/library/functions.html#func-str">str</a>). The example below demonstrates how type annotations in can be <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-annotated-assignment-stmt">included in assignment statements</a>.</p><pre>n: int = 123<br>s: str = &quot;abc&quot;</pre><p>The example below demonstrates how type annotations can be <a href="https://docs.python.org/3/glossary.html#term-function-annotation">included in function definitions</a>.</p><pre><strong>def</strong> f(x: int) -&gt; int:<br>    <strong>return</strong> x + x</pre><p>Note that no static or dynamic type checking takes place; the annotations are ignored by the interpreter.</p><pre>&gt;&gt;&gt;<strong> </strong>(f(123), f(&quot;abc&quot;))<br>(246, &#39;abcabc&#39;)</pre><h3>Annotations with More Complex and Custom Types</h3><p>The built-in <a href="https://docs.python.org/3/library/typing.html">typing</a> library provides a number of useful functions for building up more complex and also user-defined types. The example below illustrates how the <a href="https://docs.python.org/3/library/typing.html#typing.Tuple">Tuple</a> constructor can be used to specify a tuple type. Note the use of <a href="https://medium.com/python-supply/embedded-languages-via-overloading-ac942c18a65b">overloading</a> to repurpose the bracket notation that is usually used for indexing.</p><pre><strong>from</strong> typing <strong>import</strong> Tuple<br><br><strong>def</strong> repeat(si: Tuple[str, int]) -&gt; str:<br>     (s, i) = si<br>     <strong>return</strong> s * i</pre><p>It is also possible to <a href="https://docs.python.org/3/library/typing.html#newtype">specify user-defined types</a>.</p><pre><strong>from</strong> typing <strong>import</strong> NewType<br><br>UserName = NewType(&quot;UserName&quot;, str)<br><br><strong>def</strong> confirm(s: UserName) -&gt; bool:<br>    <strong>return</strong> s == &quot;Alice&quot;</pre><p>As before, note that no type checking occurs.</p><pre>&gt;&gt;&gt; (confirm(&quot;Alice&quot;), confirm(&quot;Bob&quot;), confirm(123))<br>(<strong>True</strong>, <strong>False</strong>, <strong>False</strong>)</pre><p>It is also possible to introduce <a href="https://docs.python.org/3/library/typing.html#typing.TypeVar">type variables</a>. This is particularly useful for specifying types for functions that are examples of <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a>. In the example below, the function is an example of parametric polymorphism in that it can operate on any list, regardless of the types of the items in that list.</p><pre><strong>from</strong> typing <strong>import</strong> Sequence, TypeVar<br><br>T = TypeVar(&quot;T&quot;)<br><br><strong>def</strong> first(xs: Sequence[T]) -&gt; T:<br>    <strong>return</strong> xs[0]</pre><p>This annotation would be an indication from whoever implemented it that the function first can be applied to a list of any type as long as all the elements in that list are of the same type.</p><pre>&gt;&gt;&gt; (first([1,2,3]), first([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]))<br>(1, &#39;a&#39;)</pre><p>The annotation in the above example is different from the annotation below, which indicates that the types of the items in the input list can be mixed (<em>e.g.</em>, [123, &quot;abc&quot;]) as long as they are each either an integer or a string.</p><pre><strong>from</strong> typing <strong>import</strong> Sequence, Union<br><br><strong>def</strong> first(xs: Sequence[Union[int, str]]) -&gt; Union[int, str]:<br>    <strong>return</strong> xs[0]</pre><h3>Determining Input Types</h3><p>To return to the motivating example introduced in the first paragraph of this article, suppose you are creating a unit testing framework that generates random inputs for functions in order to check that (1) they always return an output of the specified type for every input and (2) they do not raise any exceptions. You can allow users of your library to specify the input types of the functions they are trying to test via Python type annotations. This ensures you are not reinventing the wheel and that your users are not cluttering their code more than necessary with decorators or other additional information that is useful only for your framework and nothing else.</p><p>There are two distinct ways to extract the type annotations associated with a function. One approach (using concepts and techniques covered in detail in <a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">another article</a>) is to inspect the source code of the function, parse it into an abstract syntax tree, and then extract the annotations from that abstract syntax tree.</p><pre><strong>import</strong> inspect<br><strong>import</strong> ast<br><br><strong>def</strong> signature(f):<br>    <em># Parse the function and extract types from the AST.</em><br>    a = ast.parse(inspect.getsource(f))<br>    type_in = a.body[0].args.args[0].annotation.id<br>    type_out = a.body[0].returns.id<br>    <strong>return</strong> (type_in, type_out)</pre><p>One benefit of this approach is that you are extracting the original text found in the definition as a string (rather than the value or object to which it evaluates).</p><pre>&gt;&gt;&gt; Number = int<br>&gt;&gt;&gt; <strong>def</strong> double(x: Number) -&gt; Number:<br>...     <strong>return</strong> x + x<br>...<br>&gt;&gt;&gt; signature(double)<br>(&#39;Number&#39;, &#39;Number&#39;)</pre><p>Another approach is to use the <a href="https://www.python.org/dev/peps/pep-3107/#accessing-function-annotations">__annotations__</a> attribute of a function.</p><pre>&gt;&gt;&gt; double.__annotations__<br>{&#39;x&#39;: int, &#39;return&#39;: int}</pre><p>Note that because return is a reserved word in the Python concrete syntax, it is safe for it to appear as a key in a dictionary in which all other keys are names of input parameters. The variant of signature below assumes that there is only one input parameter in the function definition.</p><pre><strong>def</strong> signature(f):<br>    a = f.__annotations__<br>    type_in = [a[k] <strong>for</strong> k <strong>in</strong> a <strong>if</strong> k != &#39;return&#39;][0]<br>    type_out = a[&#39;return&#39;]<br>    <strong>return</strong> (type_in, type_out)</pre><p>When using this approach, you receive the evaluated result of the expression that appeared within the annotation context. If the original synonym used for a type (as in the first example above) is important to obtain for your application or scenario, that information may be lost after evaluation. If all you care about is the actual type and not the name of the user-defined synonym, this approach is a more direct way to obtain the annotation information.</p><pre>&gt;&gt;&gt; signature(double)<br>(int, int)</pre><p>One important point to consider once you have chosen one of the two techniques above is how you might check whether an object or value is of the type you obtained from the annotation. If the type annotation information is in the form of a string and you are checking a value of a <a href="https://docs.python.org/3/library/stdtypes.html">built-in type</a> or an object of a user-defined class, you can perform the check by extracting the name of the type and doing a string comparison.</p><pre>&gt;&gt;&gt; type(123).__name__ == &quot;int&quot;<br><strong>True</strong></pre><p>On the other hand, if the type annotation information is the form of a value or object that represents a type (such as <a href="https://docs.python.org/3/library/functions.html#int">int</a>), you can check a value is of the type in the following way.</p><pre>&gt;&gt;&gt; isinstance(123, int)<br><strong>True</strong></pre><p>A concrete example of a component in your unit testing framework is presented below. It can ingest a function that takes a single input and produces a single output. This component will generate random inputs of the appropriate type, depending on whether the input type annotation of the supplied function indicates that the input must be an integer or a floating point number. It will then check that the output type matches the function’s output type annotation and that no exceptions are raised.</p><pre><strong>import</strong> random<br><br><strong>def</strong> safe(f):<br>    (type_in, type_out) = signature(f)<br>    <br>    <strong>for</strong> i <strong>in</strong> range(10000): <em># Run 100 trials.<br>        <br>        # Generate a random input of the appropriate type.</em><br>        <strong>if</strong> type_in <strong>is</strong> int:<br>            value_in = random.randint(-2**16, (2**16)-1)<br>        <strong>if</strong> type_in <strong>is</strong> float:<br>            value_in = random.uniform(-2**16, (2**16)-1)<br>        <br>        <em># Check that output has the correct type.</em><br>        <strong>try</strong>:<br>            value_out = f(value_in)<br>            assert(isinstance(value_out, type_out))<br>        <strong>except</strong>:<br>            <strong>return</strong> <strong>False<br>    <br>    return</strong> <strong>True</strong> <em># All trials succeeded.</em></pre><p>The safe function is applied to some example inputs below. The triple function correctly returns an integer in all cases. However, the floor function incorrectly (at least, according to its type specification) returns floating point numbers when its input is not positive.</p><pre>&gt;&gt;&gt;<strong> def</strong> triple(x: int) -&gt; int:<br>...     <strong>return</strong> x + x + x<br>...<br>&gt;&gt;&gt;<strong> def</strong> floor(x: float) -&gt; int:<br>...     <strong>return</strong> int(x) <strong>if</strong> x &gt; 0 <strong>else</strong> x<br>...<br>&gt;&gt;&gt; (safe(triple), safe(floor))<br>(<strong>True</strong>, <strong>False</strong>)</pre><p>Notice that this approach allows you to create a testing component that can handle failures during the testing process without raising an exception, making it possible to build long chains of tests for many functions without worrying about unexpected termination of the Python interpreter.</p><h3>Further Reading</h3><p>Reviewing the <a href="https://www.python.org/dev/peps/pep-0484">Python Enhancement Proposal</a> associated with the type annotation feature provides important context about how the Python community views this feature and its future evolution. In particular, it is <a href="https://www.python.org/dev/peps/pep-0484/#non-goals">stated explicitly</a> that it should not be inferred from the presence of this feature that Python will ever become a language that provides native support for type checking or requires type annotations. However, the community does envision the creation of user-built libraries for these purposes and views annotations as a standardized foundation.</p><p>Some third-party libraries leverage support for type annotations to provide <a href="https://en.wikipedia.org/wiki/Type_system#Static_type_checking">static type checking</a> and even <a href="https://en.wikipedia.org/wiki/Type_inference">type inference</a>. The <a href="http://www.mypy-lang.org/">mypy library</a> can annotate Python code with type information automatically, can type-check a program statically (without running it), and can introduce run-time type checks. Other community members have written libraries that allow programmers to perform both static and run-time type checking simply by adding a decorator. One example is <a href="https://github.com/RussBaz/enforce">enforce</a>, though the project appears to be dormant and is no longer compatible with the <a href="https://docs.python.org/3/library/typing.html">typing</a> library in the latest releases of Python.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/advantages-of-type-annotations/blob/master/advantages-of-type-annotations.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/advantages-of-type-annotations"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6eb70fa631" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/advantages-of-type-annotations-6c6eb70fa631">Advantages of Type Annotations</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded Languages via Overloading]]></title>
            <link>https://medium.com/python-supply/embedded-languages-via-overloading-ac942c18a65b?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/ac942c18a65b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 06:00:04 GMT</pubDate>
            <atom:updated>2020-10-22T06:17:37.213Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are creating a Python library for building logical circuits. You would like programmers to be able to build circuits that correspond to more complex, high-level functions (<em>e.g.</em>, from equality of bit vectors to entire hashing functions). How should you approach this task? What are the right abstractions? How can you minimize the amount of extra effort programmers must put into learning your library and its various interfaces?</p><p>Python’s operator overloading features are not just a way to add syntactic convenience to your data structures. By leveraging this feature in the right way, you can greatly reduce the <em>conceptual</em> complexity of a solution by allowing programmers to use the skills they already possess. This article reviews a use case that demonstrates the value of recasting a solution as an <em>embedded language</em> within the Python syntax.</p><h3>Operator Overloading</h3><p>Python allows programmers to change the meaning of some of its syntactic constructs when these constructs are applied to objects of programmer-defined classes (the definition of Python’s syntax is discussed in more detail in a <a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">previous article</a>). Programmers can do so by defining <a href="https://docs.python.org/3/reference/datamodel.html">special methods</a> within a class definition. When the Python interpreter sees a certain operator (such as +) being applied to objects of a class that has such a special method defined (such as <a href="https://docs.python.org/3/reference/datamodel.html#object.__add__">__add__</a>), the interpreter will invoke that method.</p><p>In the example below, the class vector allows users to build objects that represent two-dimensional vectors. The class definition has a method <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__</a>.</p><pre><strong>class</strong> vector():<br>    def __init__(self, *coordinates):<br>        self.coordinates = coordinates</pre><pre><strong>def</strong> __eq__(self, other):<br>        return self.coordinates == other.coordinates</pre><p>The method __eq__ is invoked when two vector objects are supplied to the infix== operator.</p><pre>&gt;&gt;&gt; v = vector(1, 2)<br>&gt;&gt;&gt; w = vector(3, 4)<br>&gt;&gt;&gt; (v == w, v == v)<br>(False, True)</pre><h3>Embedded Language for Boolean Circuits</h3><p>An <em>embedded language</em> is a specified subset of an existing programming language (which can be called the <em>host</em> language) that serves some distinct purpose. An important benefit of embedded languages is that they reuse the existing features of the host language, which can save both implementation effort and the barrier to entry for users of the embedded language.</p><p>Returning to the motivating use case of implementing a library for logical circuits, you might consider that a Python programmer using your library <em>already knows how to use Python to implement a logical circuit</em>. Therefore, any effort the programmer spends learning to use your library is potentially wasted. How might such a programmer implement a circuit they want to evaluate on inputs?</p><p>For the purposes of this example, assume that the programmer represents bits using the Python integers 0 and 1. One approach the programmer might use is to define a function that operates on integers and uses Python&#39;s built-in logical operators on integer values.</p><pre><strong>def</strong> equal(x, y):<br>    <strong>return</strong> (x &amp; y) | ((1 - x) &amp; (1 - y))</pre><p>Below are two approaches a Python programmer might use (the first being an imperative style and the second being a functional style) to implement an equality function equals for <em>bit vectors</em> using the equality function equal for bits that is defined above. You would like your circuit library to accommodate all of these different approaches (because these approaches reflect different trade-offs that might be suitable for different use cases, or simply because programmers might have different preferences or levels of experience with Python).</p><pre><strong>def</strong> equals(xs, ys):<br>    z = 1<br>    <strong>for</strong> i <strong>in</strong> range(len(xs)):<br>        z = z &amp; equal(xs[i], ys[i])<br>    <strong>return</strong> z</pre><pre><strong>def</strong> equals(xs, ys):<br>    <strong>from</strong> functools <strong>import</strong> reduce<br>    es = [equal(x, y) <strong>for</strong> (x, y) <strong>in</strong> zip(xs, ys)]<br>    <strong>return</strong> reduce((<strong>lambda</strong> e0, e1: e0 &amp; e1), es)</pre><p>Under its usual interpretation in Python (<em>i.e.</em>, when it is applied to lists of integers), the equals function can be used to determine the equality of bit vectors of equal length.</p><pre>&gt;&gt;&gt; equals([0,1,1], [0,1,1])<br>1</pre><p>Using overloading, it is possible to provide new definitions for the built-in &amp;, | and - operators that <em>programmers already used</em> to define the equal and equals functions. The circuit class definition below includes the <a href="https://docs.python.org/3/reference/datamodel.html#object.__or__">__or__</a>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__and__">__and__</a>, and <a href="https://docs.python.org/3/reference/datamodel.html#object.__rsub__">__rsub__</a> methods that correspond to the way in which these three infix operators are used.</p><pre><strong>class</strong> circuit():<br>    <strong>def</strong> __init__(self, op=&#39;bit&#39;, args=None):<br>        self.op = op<br>        self.args = [] <strong>if</strong> args <strong>is</strong> None <strong>else</strong> args</pre><pre><strong>def</strong> __or__(self, other):<br>        <strong>return</strong> circuit(&#39;or&#39;, [self, other])</pre><pre><strong>def</strong> __and__(self, other):<br>        <strong>return</strong> circuit(&#39;and&#39;, [self, other])</pre><pre><strong>def</strong> __rsub__(self, other):<br>        <strong>if</strong> not isinstance(other, int) <strong>or</strong> other != 1:<br>            <strong>raise</strong> ValueError(&#39;can only subtract from 1&#39;)<br>        <strong>return</strong> circuit(&#39;not&#39;, [self])</pre><pre><strong>def</strong> __repr__(self):<br>        <strong>return</strong> &#39;circuit(&quot;&#39; + self.op + &#39;&quot;, &#39; + str(self.args) + &#39;)&#39;</pre><pre><strong>def</strong> __str__(self):<br>        <strong>return</strong> self.__repr__()</pre><p>To make it easier to see the circuits after they have been constructed, the definition above also includes a recursive <a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__">__repr__</a> method and an equivalent <a href="https://docs.python.org/3/reference/datamodel.html#object.__str__">__str__</a> method. The first method is invoked when Python attempts to display an object of the class (<em>e.g.</em>, in an interactive prompt) and the second is invoked when the built-in Python <a href="https://docs.python.org/3/library/stdtypes.html#str">str</a> function is applied to an object of the class circuit.</p><p>A programmer can now build a circuit using familiar infix operators. The only difference is that instead of using Python integers to represent the bits that constitute the inputs (<em>i.e.</em>, base cases), programmers can use circuit objects that represent bit constants.</p><pre>c0 = circuit(&quot;bit&quot;, 0)<br>c1 = circuit(&quot;bit&quot;, 1)<br>c2 = 1 — (c0 &amp; c1)</pre><p>More importantly, programmers can now <em>reuse without modification</em> the equality functions that have already been defined. However, those same functions now generate entire equality circuits (rather than only computing the result of evaluating those circuits).</p><pre>&gt;&gt;&gt; equal(c1, c2)<br>circuit(&quot;or&quot;, [circuit(&quot;and&quot;, [circuit(&quot;bit&quot;, 1), circuit(&quot;not&quot;, [circuit(&quot;and&quot;, [circuit(&quot;bit&quot;, 0), circuit(&quot;bit&quot;, 1)])])]), circuit(&quot;and&quot;, [circuit(&quot;not&quot;, [circuit(&quot;bit&quot;, 1)]), circuit(&quot;not&quot;, [circuit(&quot;not&quot;, [circuit(&quot;and&quot;, [circuit(&quot;bit&quot;, 0), circuit(&quot;bit&quot;, 1)])])])])])</pre><p>Even the more complex equals method works seamlessly whether it is given lists of bit vectors or lists of base case circuits.</p><pre>&gt;&gt;&gt; equals([c0, c1], [c0, c1])<br>circuit(&quot;and&quot;, [circuit(&quot;or&quot;, [circuit(&quot;and&quot;, [circuit(&quot;bit&quot;, 0), circuit(&quot;bit&quot;, 0)]), circuit(&quot;and&quot;, [circuit(&quot;not&quot;, [circuit(&quot;bit&quot;, 0)]), circuit(&quot;not&quot;, [circuit(&quot;bit&quot;, 0)])])]), circuit(&quot;or&quot;, [circuit(&quot;and&quot;, [circuit(&quot;bit&quot;, 1), circuit(&quot;bit&quot;, 1)]), circuit(&quot;and&quot;, [circuit(&quot;not&quot;, [circuit(&quot;bit&quot;, 1)]), circuit(&quot;not&quot;, [circuit(&quot;bit&quot;, 1)])])])])</pre><h3>Portable or Specialized Embeddings via Inheritance</h3><p>The advantage of the definition of circuit in the section above is that programmers can <em>build</em> new circuits using existing built-in Python operators. However, in order to <em>inspect</em> or <em>traverse</em> the circuit data structure, programmers must become familiar with your class definition. Using <a href="https://docs.python.org/3/tutorial/classes.html#inheritance">inheritance</a>, you can address this second obstacle.</p><p>The variant of the circuit class below represents circuits as dictionaries (or, more precisely, as objects of classes that inherit all the features of dictionaries).</p><pre><strong>class</strong> circuit(dict):<br>    <strong>def</strong> __or__(self, other):<br>        <strong>return</strong> circuit({&#39;or&#39;: [self, other]})</pre><pre><strong>def</strong> __and__(self, other):<br>        <strong>return</strong> circuit({&#39;and&#39;: [self, other]})</pre><pre><strong>def</strong> __rsub__(self, other):<br>        <strong>if</strong> <strong>not</strong> isinstance(other, int) <strong>or</strong> other != 1:<br>            <strong>raise</strong> ValueError(&#39;can only subtract from 1&#39;)<br>        <strong>return</strong> circuit({&#39;not&#39;: [self]})</pre><p>Because circuits built by programmers are now also dictionaries, it is easier to use existing built-in libraries to perform common operations. For example, a formatted JSON string representation of a circuit can be emitted using the <a href="https://docs.python.org/3/library/json.html">json</a> library. In the example below, a JSON representation of the bit vector equality circuit is constructed.</p><pre>&gt;&gt;&gt; c0 = circuit({&quot;bit&quot;: 0})<br>&gt;&gt;&gt; c1 = circuit({&quot;bit&quot;: 1})<br>&gt;&gt;&gt; import json<br>&gt;&gt;&gt; print(json.dumps(equals([c0, c1], [c0, c1])))<br>{&quot;and&quot;: [{&quot;or&quot;: [{&quot;and&quot;: [{&quot;bit&quot;: 0}, {&quot;bit&quot;: 0}]}, {&quot;and&quot;: [{&quot;not&quot;: [{&quot;bit&quot;: 0}]}, {&quot;not&quot;: [{&quot;bit&quot;: 0}]}]}]}, {&quot;or&quot;: [{&quot;and&quot;: [{&quot;bit&quot;: 1}, {&quot;bit&quot;: 1}]}, {&quot;and&quot;: [{&quot;not&quot;: [{&quot;bit&quot;: 1}]}, {&quot;not&quot;: [{&quot;bit&quot;: 1}]}]}]}]}</pre><p>For another example of this approach that is more specialized, consider the circuit class below that is derived from the <a href="https://networkx.org/documentation/networkx-1.7/reference/classes.graph.html">Graph</a> class in the <a href="https://networkx.org/">NetworkX</a> library. In this implementation, each circuit object is a graph in which nodes correspond to base cases or operations and edges connect operation nodes with their operands. The method corresponding to a binary operator such as &amp; performs the following steps:</p><ul><li>it accepts two input graphs (each representing an entire circuit, with the output node as the first entry in its node list),</li><li>it combines these two graphs into a new graph in which each node’s name is extended to reflect the path to that node,</li><li>it adds a new node corresponding to the binary operation, and</li><li>it adds edges between this new output node and the root nodes of the two input graphs.</li></ul><p>Note that in order to have mathematical notation within the node labels in the final rendering of the circuit, the <a href="https://en.wikipedia.org/wiki/LaTeX">LaTeX</a> notation is used for the operator name strings.</p><pre><strong>from</strong> networkx <strong>import</strong> Graph, union</pre><pre><strong>class</strong> circuit(Graph):<br>    <strong>def</strong> __init__(self, arg=<strong>None</strong>):<br>        Graph.__init__(self)<br>        <strong>if</strong> arg <strong>is</strong> <strong>not</strong> <strong>None</strong>:<br>            self.add_nodes_from([str(arg)])</pre><pre><strong>def</strong> __or__(self, other):<br>        c = union(<br>            circuit(&quot;$\\vee$&quot;),<br>            union(self, other, rename=(&quot;l-&quot;, &quot;r-&quot;))<br>        )<br>        c.add_edges_from([<br>            (&quot;$\\vee$&quot;, &quot;l-&quot; + list(self.nodes)[0]),<br>            (&quot;$\\vee$&quot;, &quot;r-&quot; + list(other.nodes)[0])<br>        ])<br>        <strong>return</strong> c</pre><pre><strong>def</strong> __and__(self, other):<br>        c = union(<br>            circuit(&quot;$\\wedge$&quot;),<br>            union(self, other, rename=(&quot;l-&quot;, &quot;r-&quot;))<br>        )<br>        c.add_edges_from([<br>            (&quot;$\\wedge$&quot;, &quot;l-&quot; + list(self.nodes)[0]),<br>            (&quot;$\\wedge$&quot;, &quot;r-&quot; + list(other.nodes)[0])<br>        ])<br>        <strong>return</strong> c</pre><pre><strong>def</strong> __rsub__(self, other):<br>        <strong>if</strong> <strong>not</strong> isinstance(other, int) <strong>or</strong> other != 1:<br>            <strong>raise</strong> ValueError(&#39;can only subtract from 1&#39;)<br>        c = union(circuit(&quot;$\\neg$&quot;), self, rename=(&quot;&quot;, &quot;n-&quot;))<br>        c.add_edges_from([(&quot;$\\neg$&quot;, &quot;n-&quot;+list(self.nodes)[0])])<br>        <strong>return</strong> c</pre><p>This approach makes it possible to render a graph diagram directly from a circuit object using the NetworkX library. To demonstrate how a programmer can accomplish this, consider the following circuit c built using the original equals method (note that it has been unmodified and yet works with objects of the newest variant of circuit).</p><pre>c = equals(<br>    [circuit(&#39;$x_0$&#39;), circuit(&#39;$x_1$&#39;)], <br>    [circuit(&#39;$y_0$&#39;), circuit(&#39;$y_1$&#39;)]<br>)</pre><p>Because c inherits all the features of a NetworkX Graph object, a programmer can inspect its nodes and edges. In the example below, the last three nodes and the number of edges in the circuit graph are extracted. Notice that each node name is a string that describes the path to that node from the circuit&#39;s overall output node (with &#39;l&#39; and &#39;r&#39; representing left-hand and right-hand subgraphs, respectively).</p><pre>&gt;&gt;&gt; (list(c.nodes)[-3:], len(c.edges))<br>([&#39;r-r-l-n-$x_1$&#39;, &#39;r-r-r-$\\neg$&#39;, &#39;r-r-r-n-$y_1$&#39;], 18)</pre><p>The following function is convenient for rendering the graph. It takes a node name string, splits it into its constituent parts (representing the path from the output node), and calculates a horizontal and vertical coordinate for that node.</p><pre><strong>def</strong> position(n):<br>    <em># Generate coordinates based on the path<br>    # encoded in the node name.</em><br>    x = sum(<br>        {&#39;l&#39;:-1, &#39;r&#39;:1}.get(c, 0)/(2**(i+3)) <br>        <strong>for</strong> (i, c) <strong>in</strong> enumerate(n.split(&#39;-&#39;))<br>    )<br>    y = n.count(&#39;-&#39;)/8<br>    <strong>return</strong> (x, y)</pre><p>With the help of the position function, rendering the circuit c as a graph is straightforward using the <a href="https://networkx.org/documentation/latest/reference/generated/networkx.drawing.nx_pylab.draw_networkx">draw_networkx</a> function. The positions for the rendered nodes are specified by building a dictionary using position and the labels for the rendered nodes are obtained by taking the last component of the node names in c.</p><pre><strong>from</strong> networkx <strong>import</strong> draw_networkx<br>draw_networkx(<br>    c,<br>    pos=dict((n, position(n)) <strong>for</strong> n <strong>in</strong> c.nodes),<br>    labels=dict((n, n.split(&#39;-&#39;)[-1]) <strong>for</strong> n <strong>in</strong> c.nodes),<br>    node_size=1000,<br>    node_color=&quot;orange&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*dlPjdKITh-0xL-oRxg3aAg.png" /><figcaption>An equality circuit on two input bit vectors (𝑥₀, 𝑥₁) and (𝑦₀, 𝑦₁) that is defined using Python syntax and rendered as a graph using the NetworkX library.</figcaption></figure><h3>Further Reading</h3><p>This article presented a brief overview of <a href="https://docs.python.org/3/reference/datamodel.html#special-method-names">operator overloading in Python</a>, with a motivating example involving a number of <a href="https://en.wikipedia.org/wiki/Domain-specific_language#External_and_Embedded_Domain_Specific_Languages">embedded domain-specific languages</a> for defining circuits. A Python library that addresses exactly the same circuit construction use case considered in this article is <a href="https://pypi.org/project/circuitry/">circuitry</a>, which defines an embedded language for constructing circuits as defined in the <a href="https://pypi.org/project/circuit/">circuit</a> library. Other examples of feature-rich and widely used domain-specific languages embedded inside Python include the <a href="https://www.djangoproject.com/">Django</a> web framework and the <a href="https://pandas.pydata.org/">pandas</a> data analysis library. However, even small built-in libraries such as <a href="https://docs.python.org/3/library/typing.html">typing</a> use operator overloading to provide a more streamlined experience for programmers.</p><p>Many other programming languages support some form of <a href="https://en.wikipedia.org/wiki/Operator_overloading">operator overloading</a>, as well as the introduction of custom infix, prefix, and even postfix operators. <a href="https://en.wikipedia.org/wiki/Operator_overloading#Catalog">Some languages</a> have both of these features. A more general term for the operator overloading capability is <a href="https://en.wikipedia.org/wiki/Ad_hoc_polymorphism"><em>ad hoc polymorphism</em></a>: the ability to provide multiple definitions for the same syntactic construct (with either the interpreter or compiler determining which definition to use based on the types of the inputs). Other, distinct types of polymorphism exist as well, such as <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism"><em>parametric polymorphism</em></a>: the ability to apply exactly the same function (having the same syntactic definition) to arguments of different types. You might notice that the definitions of equal and equals in this article are actually examples of parametric polymorphism.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/embedded-languages-via-overloading/blob/master/embedded-languages-via-overloading.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/embedded-languages-via-overloading"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac942c18a65b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/embedded-languages-via-overloading-ac942c18a65b">Embedded Languages via Overloading</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing and Transforming Abstract Syntax]]></title>
            <link>https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7d3da23b14f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[code-transformation]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 00:02:06 GMT</pubDate>
            <atom:updated>2021-04-25T21:57:10.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THz8aEnJtdBNXGGFxoYCwA.png" /></figure><p>You manage a large Python codebase that interacts with another vendor’s library. A new version of this library is not backwards compatible: it has switched from lists to iterators throughout its API. This is a problem because your codebase uses <a href="https://docs.python.org/3/library/functions.html?highlight=slice#slice">slice notation</a> on list values throughout, which must now be replaced with calls to <a href="https://docs.python.org/3/library/itertools.html#itertools.islice">islice</a>. You are tasked with quantifying the extent to which the codebase under your management must be modified, and with designing and/or implementing a process for performing the updates across this codebase. How can you avoid having to manually identify and rewrite every occurrence of slice notation? Is there a way both to measure the extent of the problem and to perform the necessary code transformations in an automated way?</p><p>More generally, the ability to work directly with the abstract syntax data structures of a language can be useful in at least two kinds of scenarios.</p><ul><li>It may be necessary to <em>analyze</em> code (possibly a very large amount of code) in an automated way to obtain some useful information (<em>e.g.</em>, whether patterns that may represent vulnerabilities or errors exist, where and how often a language feature is used, the portion of the code for which tests and documentation are present, and so on).</li><li>It may be necessary to <em>transform</em> code (again, possibly a very large amount of code) in some way (<em>e.g.</em>, to update its compatibility with a newer version of an API, to transpile it to another language, and so on).</li></ul><p>Python’s built-in libraries include powerful modules that make it possible to retrieve and operate over parse trees or <em>abstract syntax trees</em> (ASTs) of modules, classes, and functions/methods. This article provides an overview of the Python syntax definition, how to build and operate on abstract syntax trees, and some use cases. With this information in hand, you should be ready to start writing Python code that examines and transforms other Python code.</p><h3>Abstract Syntax Grammar and Data Structure</h3><p>For any given programming language, the <em>concrete syntax</em> corresponds to the actual strings of characters that make up a program, and the <em>abstract syntax</em> corresponds to the data structure instances that a parser for that language generates from a string of characters (and which may subsequently be processed by an interpreter or a compiler). An instance of the abstract syntax data structure is sometimes called a <em>parse tree</em>, an <em>abstract syntax tree</em>, or an <em>AST</em>.</p><p>The definitions of abstract syntax grammar for Python is presented in the <a href="https://docs.python.org/3/library/ast.html#abstract-grammar">documentation for the </a><a href="https://docs.python.org/3/library/ast.html#abstract-grammar">ast module</a>. The ast module itself includes an implementation of the data structure corresponding to the grammar definition, as well as associated functionalities (such as features that enable parsing a concrete syntax string into an AST instance and performing transformations on an AST instance).</p><pre><strong>import</strong> ast<br><br><em># Programmatically build an AST for the</em><br><em># Python concrete syntax expression `-5`.</em><br>node =\<br>  ast.UnaryOp(<br>    ast.USub(),<br>    ast.Num(5, lineno=0, col_offset=0),<br>    lineno=0,<br>    col_offset=0<br>  )</pre><p>The dump function returns a string representation of the data structure.</p><pre>&gt;&gt;&gt; ast.dump(node)<br>&#39;UnaryOp(op=USub(), operand=Constant(value=5))&#39;</pre><p>You can use the <a href="https://docs.python.org/3/library/inspect.html">inspect</a> module to retrieve the concrete syntax of the body of a Python function definition.</p><pre>&gt;&gt;&gt; <strong>def</strong> f(x):<br>...     <strong>return</strong> x + 2<br>...<br>&gt;&gt;&gt;<strong> import</strong> inspect<br>&gt;&gt;&gt; inspect.getsource(f)<br>&#39;def f(x):\n    return x + 2\n&#39;</pre><p>You can then parse the concrete syntax using <a href="https://docs.python.org/3/library/ast.html#ast.parse">ast.parse()</a> to generate an instance of the abstract syntax data structure.</p><pre>&gt;&gt;&gt; t = ast.parse(inspect.getsource(f))<br>&gt;&gt;&gt; ast.dump(t)<br>&quot;Module(body=[FunctionDef(name=&#39;f&#39;, args=arguments(posonlyargs=[], args=[arg(arg=&#39;x&#39;, annotation=None, type_comment=None)], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Return(value=BinOp(left=Name(id=&#39;x&#39;, ctx=Load()), op=Add(), right=Constant(value=2, kind=None)))], decorator_list=[], returns=None, type_comment=None)], type_ignores=[])&quot;</pre><p>How can this data structure be inspected and traversed using the ast API? Every instance of the data structure is also a node in the tree that represents the root of the module, statement, or expression that was parsed to build it. You can determine what fields exist in the node using the _fields attribute. For example, you can retrieve the body of the function definition above in the following way. Notice that the body field is a list of AST nodes in which the first (and only) node is the function definition.</p><pre>&gt;&gt;&gt; if &#39;body&#39; in t._fields and len(t.body) &gt; 0:<br>...     stmt = t.body[0]<br>...     print(isinstance(stmt, ast.FunctionDef))<br>...<br><strong>True</strong></pre><p>You can retrieve the single statement in the body of the function by referencing the <a href="https://docs.python.org/3/library/ast.html#abstract-grammar">abstract syntax definition</a> and working your way down through the various parameters of the data structure.</p><pre>&gt;&gt;&gt; if &#39;body&#39; in stmt_fun._fields and len(stmt_fun.body) &gt; 0:<br>...     stmt_return = stmt_fun.body[0]<br>...     print(isinstance(stmt_return, ast.Return))<br><strong>...<br>True</strong></pre><p>Going deeper, you can retrieve the expression inside the return statement in the following way.</p><pre>&gt;&gt;&gt; if &#39;value&#39; in stmt_return._fields:<br>...    expr_add = stmt_return.value<br>...    print(isinstance(expr_add, ast.BinOp))<br>...<br><strong>True</strong></pre><p>Finally, you can extract the expression operator and its individual arguments.</p><pre>&gt;&gt;&gt; expr_add.left<br>&lt;_ast.Name object at 0x05FC1178&gt;<br>&gt;&gt;&gt; expr_add.left.id<br>x<br>&gt;&gt;&gt; expr_add.op<br>&lt;_ast.Add object at 0x03A97A78&gt;<br>&gt;&gt;&gt; expr_add.right<br>&lt;_ast.Constant object at 0x05FC17C0&gt;<br>&gt;&gt;&gt; expr_add.right.n<br>2</pre><h3>Analyzing an Abstract Syntax Tree</h3><p>The ast API allows you to programmatically write you own functions for operating on Python ASTs. The example below collects all the variables in an AST (as long as the AST consists of the specific kinds of nodes that are handled by the various if branches in the body of the function).</p><pre><strong>def</strong> collect_variables(a):<br>    <strong>if</strong> type(a) <strong>is</strong> ast.Module:<br>        <strong>return</strong> [v <strong>for</strong> s <strong>in</strong> a.body <strong>for</strong> v <strong>in</strong> collect_variables(s)]<br>    <br>    <strong>elif</strong> type(a) <strong>is</strong> ast.FunctionDef:<br>        vs = [v <strong>for</strong> s <strong>in</strong> a.body <strong>for</strong> v <strong>in</strong> collect_variables(s)]<br>        <strong>return</strong> [a.name] + vs</pre><pre><strong>elif</strong> type(a) <strong>is</strong> ast.Assign:<br>        vs = [v <strong>for</strong> s <strong>in</strong> a.targets <strong>for</strong> v <strong>in</strong> collect_variables(s)]<br>        <strong>return</strong> vs + collect_variables(a.value)<br>    <br>    <strong>elif</strong> type(a) <strong>is</strong> ast.Return:<br>        <strong>return</strong> collect_variables(a.value)</pre><pre><strong>elif</strong> type(a) <strong>is</strong> ast.Name:<br>        <strong>return</strong> [a.id]</pre><pre><strong>elif</strong> type(a) <strong>is</strong> ast.BinOp:<br>        <strong>return</strong>\<br>            collect_variables(a.left) + collect_variables(a.right)<br><br><strong>else</strong>:<br>    print(type(a)) <em># Display trees not captured by cases above.</em><br>    <strong>return</strong> []</pre><p>Invoking the collect_variables function on an example yields a list of all the variables encountered during the recursive traversal. Note that because there was no explicit case handling constants, they are displayed by the print statement at the end of the function.</p><pre>&gt;&gt;&gt;<strong> def</strong> f(x, y):<br>...     a = b<br>...     u = 1 + 2<br>...     z = x + y<br>...     <strong>return</strong> z<br>...<br>&gt;&gt;&gt; a = ast.parse(inspect.getsource(f))<br>&gt;&gt;&gt; collect_variables(a)<br>&lt;class &#39;_ast.Constant&#39;&gt;<br>&lt;class &#39;_ast.Constant&#39;&gt;<br>[&#39;f&#39;, &#39;a&#39;, &#39;b&#39;, &#39;u&#39;, &#39;z&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;]</pre><p>You can instead use the ast.walk() function to traverse a tree if you are not worried about its internal structure but wish to see and process all of its nodes in some way (usually, to produce some kind of less granular aggregate analysis). The example below performs the same task as the function collect_variables above.</p><pre>&gt;&gt;&gt; vs = []<br>&gt;&gt;&gt;<strong> for</strong> node <strong>in</strong> ast.walk(a):<br>...     <strong>if</strong> isinstance(node, ast.FunctionDef):<br>...         vs.append(node.name)<br>...     <strong>if</strong> isinstance(node, ast.Name):<br>...         vs.append(node.id)<br>...<br>&gt;&gt;&gt; vs<br>[&#39;f&#39;, &#39;a&#39;, &#39;b&#39;, &#39;u&#39;, &#39;z&#39;, &#39;z&#39;, &#39;x&#39;, &#39;y&#39;]</pre><p>Returning to the motivating example in the first paragraph of this article, this approach can be used to find all occurrences of slice notation.</p><pre><strong>def</strong> slice_occurrences(a):<br>    occurs = 0<br>    <strong>for</strong> node <strong>in</strong> ast.walk(a):<br>        <strong>if</strong> isinstance(node, ast.Subscript):<br>            <strong>if</strong> isinstance(node.slice, ast.Slice):<br>                occurs += 1<br>    <strong>return</strong> occurs</pre><p>Using the above function on some examples yields the expected results.</p><pre>&gt;&gt;&gt;<strong> def</strong> f(xs):<br>...     <strong>return</strong> xs[0:10] + xs[20:30]<br>...<br>&gt;&gt;&gt;<strong> def</strong> g(xs):<br>...     <strong>return</strong> [xs[0], xs[1]]<br>...<br>&gt;&gt;&gt; slice_occurrences(ast.parse(inspect.getsource(f)))<br>2<br>&gt;&gt;&gt; slice_occurrences(ast.parse(inspect.getsource(g)))<br>0</pre><h3>Transforming an Abstract Syntax Tree</h3><p>You can use the ast.NodeVisitor and ast.NodeTransformer base classes to create your own algorithms that traverse or modify ASTs. This allows your implementation to have a more structured approach than one that uses ast.walk, while also allowing you to avoid explicitly handling every possible kind of AST node in your implementation as was done in the first example involving collect_variables.</p><p>In the example below, the DisplayVariables class visits every node and, if it is a function definition or a variable occurrence, displays its name. The call to generic_visit is necessary to ensure that, despite our replacing the particular methods for the Name and FunctionDef node types, the ast.NodeVisitor class can continue to recursively traverse the subtrees of these node types.</p><pre><strong>class</strong> DisplayVariables(ast.NodeVisitor):<br>    <strong>def</strong> visit_Name(self, node):<br>        print(node.id)<br>        self.generic_visit(node)</pre><pre><strong>def</strong> visit_FunctionDef(self, node):<br>        print(node.name)<br>        self.generic_visit(node) <em># Needed for overriding method.</em></pre><p>Any class derived from NodeVisitor can be applied to an AST instance in the following way.</p><pre>&gt;&gt;&gt;<strong> def</strong> f(x, y):<br>...     a = b<br>...     u = 1 + 2<br>...     z = x + y<br>...     <strong>return</strong> z<br>...<br>&gt;&gt;&gt; a = ast.parse(inspect.getsource(f))<br>&gt;&gt;&gt; DisplayVariables().visit(a)<br>f<br>a<br>b<br>u<br>z<br>x<br>y<br>z</pre><p>In the example below, the ChangeVariable class is a transformer that visits every node. If the node is a variable (<em>i.e.</em>, x in the Python concrete syntax), the variable node is replaced with a subtree corresponding to the Python concrete syntax for a dictionary access (<em>i.e.</em>, data[&#39;x&#39;] in the Python concrete syntax).</p><pre><strong>class</strong> ChangeVariables(ast.NodeTransformer):<br>    <strong>def</strong> visit_Name(self, node): <em># Only transform `Name` nodes.</em><br>        a =\<br>          ast.copy_location(<br>            ast.Subscript(<br>              value=ast.Name(id=&#39;data&#39;, ctx=ast.Load()),<br>              slice=ast.Index(value=ast.Str(s=node.id)),<br>              ctx=node.ctx<br>            ),<br>            node<br>          )<br>        <strong>return</strong> a</pre><p>As with NodeVisitor, any class derived from NodeTransformer can be applied to an AST instance.</p><pre>&gt;&gt;&gt;<strong> def</strong> f(x, y):<br>...     <strong>return</strong> x + y<br>...<br>&gt;&gt;&gt; a = ChangeVariables().visit(ast.parse(inspect.getsource(f)))</pre><p>You can use the <a href="https://astor.readthedocs.io/">astor</a> module to convert an AST back into concrete syntax. This is a straightforward way to write transformed code back to a file.</p><pre>&gt;&gt;&gt; <strong>import</strong> astor<br>&gt;&gt;&gt; print(astor.to_source(a))<br>def f(x, y):<br>    return data[&#39;x&#39;] + data[&#39;y&#39;]</pre><p>Returning to the motivating example in the first paragraph of this article, the ChangeSlices transformer below replaces all subtrees that consist of slice notation with a subtree that consists of a call to <a href="https://docs.python.org/3/library/itertools.html#itertools.islice">islice</a>. Notice that it is necessary to preserve the subtrees corresponding to the upper and lower bounds of the slice range and make them the new arguments to islice. This example only handles cases where both the upper and lower bounds are explicit in the original slice notation.</p><pre><strong>class</strong> ChangeVariables(ast.NodeTransformer):<br>    <strong>def</strong> visit_Subscript(self, node):<br>        a =\<br>          ast.copy_location(<br>            ast.Call(<br>              func=ast.Name(id=&#39;islice&#39;, ctx=ast.Load()),<br>              args=[<br>                ast.Name(id=node.value.id, ctx=ast.Load()),<br>                node.slice.lower,<br>                node.slice.upper<br>              ],<br>              ctx=node.ctx,<br>              keywords=[]<br>            ),<br>            node<br>          )<br>        <strong>return</strong> a</pre><p>Below, the ChangeSlices transformer is called on an example input.</p><pre>&gt;&gt;&gt; def f(xs):<br>...     return xs[0:10]<br>...<br>&gt;&gt;&gt; a = ChangeVariables().visit(ast.parse(inspect.getsource(f)))<br>&gt;&gt;&gt; print(astor.to_source(a))<br>def f(xs):<br>    return islice(xs, 0, 10)</pre><p>Notice that this approach works even if the parameter subexpressions within each instance of slice notation are highly complex because the subtrees in the AST are simply inserted into the new node that invokes islice. Thus, this is both a general and a scalable approach for replacing instances of slice notation with islice throughout a large codebase.</p><h3>Further Reading</h3><p>This article briefly introduced some concepts involved in defining and implementing a programming language (such as <a href="https://en.wikipedia.org/wiki/Abstract_syntax">abstract syntax</a> and <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">abstract syntax trees</a>), as well as a number of tools for writing Python programs that can analyze and transform other Python programs. These features allow Python to support families of techniques such as <a href="https://en.wikipedia.org/wiki/Reflection_(computer_programming)">reflection</a>, <a href="https://en.wikipedia.org/wiki/Source-to-source_compiler">source-to-source compilation</a>, and <a href="https://en.wikipedia.org/wiki/Static_analysis">static analysis</a>, and it can be worthwhile to learn more about these in order to expand the set of tools available to you on your next project. This article also provided a brief overview of the Python language definition; you can explore the full language definition (including all the various constructs and the concrete and abstract syntax representations) in the <a href="https://docs.python.org/3/reference/index.html">Python Language Reference</a>.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/analyzing-and-transforming-abstract-syntax/blob/master/analyzing-and-transforming-abstract-syntax.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/analyzing-and-transforming-abstract-syntax"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d3da23b14f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/analyzing-and-transforming-abstract-syntax-d7d3da23b14f">Analyzing and Transforming Abstract Syntax</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterators, Generators, and Uncertainty]]></title>
            <link>https://medium.com/python-supply/iterators-generators-and-uncertainty-a3e7f85183b?source=rss----ef71c9b0089---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3e7f85183b</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Andrei Lapets]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 23:26:51 GMT</pubDate>
            <atom:updated>2020-10-14T23:26:51.051Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you are working on a Python API that provides access to a real-time data stream (perhaps from an array of sensors or from a web service that handles user requests). You would like to deliver to the consumers of your API a simple but flexible abstraction that allows them to operate on new items from the stream when they choose to do so. Furthermore, you would like the API to allow users to do the following three things:</p><ul><li>specify fall-back or default data streams (<em>e.g.</em>, if their first choice of stream is exhausted);</li><li>interleave items coming from multiple streams (presenting them as a single, new stream); and</li><li>process the items from a stream in parallel using multiprocessing.</li></ul><p>What abstraction should you use? How much of it must be custom-built and how much can be done using native Python features? When working with data streams, state spaces, and other abstractions that represent large or unbounded structures, it can be tempting to custom-build solutions that may become increasingly complex and difficult to maintain. Understanding a range of features that are already available in a language or its built-in libraries can help mitigate this while saving significant time and effort (both your own and that of others who build upon your work).</p><p>Iterators and generators are powerful tools in the Python language that have compelling applications in a number of contexts. This article reviews how they are defined, how they can be used, how they are related to one another, and how they can help you work in an elegant and flexible way with data structures and data streams of an unknown or infinite size.</p><h3>Iterables, Iterators, and Generators</h3><p>When discussing Python, the terms <em>iterable</em>, <em>iterator</em>, and <em>generator</em> often appear in similar contexts or are even used interchangeably. These language features also solve similar problems. This can lead to some confusion, but there is a reason that on occasion these are conflated.</p><p>One way to understand the term <em>iterator</em> is that it refers to <em>any</em> Python data structure that <em>has an interface</em> that supports iteration over objects one at a time. A data structure is <em>iterable</em> if there is <em>at least one way</em> to construct an iterator that traverses it in some way. On the other hand, a <em>generator</em> is a particular kind of data structure, defined in a specific way within Python, that maintains an internal state and constructs or retrieves zero or more objects or values one at a time.</p><p>Thus, a generator by virtue of its characteristics can have an interface that allows it to qualify as an iterator, which consequently also makes it an iterable. In fact, all generators are iterators and iterable. However, not all iterators or iterable data structures are generators because there exist other approaches for implementing a Python object possessing the kind of interface an iterator or iterable is expected to have.</p><h3>Iterators</h3><p>If you want to implement an iterator data structure directly, you need to include a special method __next__ in the class definition, which will be invoked whenever the built-in function <a href="https://docs.python.org/3/library/functions.html#next">next</a> is applied to an instance of that data structure. The skips data structure below can emit every other positive integer via its definition of a __next__ method.</p><pre><strong>class</strong> skips:<br>    <strong>def</strong> __init__(self):<br>        self.integer = 0<br><br>    <strong>def</strong> __next__(self):<br>        self.integer += 2<br>        <strong>return</strong> self.integer</pre><p>Now it is possible to use the built-in <a href="https://docs.python.org/3/library/functions.html#next">next</a> function to retrieve each item one at a time from an instance of the skips data structure.</p><pre>&gt;&gt;&gt; ns = skips()<br>&gt;&gt;&gt; [next(ns), next(ns), next(ns)]<br>[2, 4, 6]</pre><p>The number of items over which the data structure will iterate can be limited by raising the StopIteration exception when more items can not (or should not) be returned.</p><pre><strong>class</strong> skips:<br>    <strong>def</strong> __init__(self, start, end):<br>        self.integer = start-2<br>        self.end = end<br><br>    <strong>def</strong> __next__(self):<br>        self.integer += 2<br>        <strong>if</strong> self.integer &gt; self.end:<br>            <strong>raise</strong> <strong>StopIteration</strong><br>        <strong>return</strong> self.integer</pre><p>It is then the responsibility of any code that uses an instance of this iterator to catch this exception and handle it appropriately. It is worth acknowledging that this is a somewhat unusual use of a language feature normally associated with catching errors (because an iterator being exhausted is not always an error condition).</p><pre>&gt;&gt;&gt; ns = skips(0, 10)<br>&gt;&gt;&gt;<strong> while</strong> <strong>True</strong>:<br>...     <strong>try</strong>:<br>...         print(next(ns))<br>...     <strong>except</strong> <strong>StopIteration</strong>:<br>...         <strong>break<br>...<br></strong>0<br>2<br>4<br>6<br>8<br>10</pre><h3>Iterables</h3><p>In Python, there is a distinction between an <em>iterator</em> and an <em>iterable data structure</em>. This distinction is useful to maintain for a variety of reasons, including the ones below.</p><ul><li>You may not want to clutter a data structure (as it may represent a spreadsheet, a database table, a large graph, and so on) with the state necessary to keep track of an iteration process.</li><li>You may want the data structure to support <em>multiple</em> iterators, either semantically (<em>e.g.</em>, iteration over rows versus over columns) or in terms of implementation (<em>e.g.</em>, breadth-first search versus depth-first search).</li><li>You may want to make it easy to <em>reset</em> iteration without fiddling with the internal state of a data structure instance (<em>i.e.</em>, resetting a traversal of the data structure instance could involve simply creating a fresh iterator).</li></ul><p>As an example, consider a data structure interval that represents all positive integers in some range. Users might be allowed to obtain two different kinds of iterators for an instance of this data structure: those that iterate over only the even integers and those that iterate over only the odd integers.</p><pre><strong>class</strong> interval:<br>    <strong>def</strong> __init__(self, lower, upper):<br>        self.lower = lower<br>        self.upper = upper<br><br>    <strong>def</strong> evens(self):<br>        <strong>return</strong> skips(<br>            self.lower + (0 <strong>if</strong> (self.lower % 2) == 0 <strong>else</strong> 1),<br>            self.upper<br>        )<br>    <br>    <strong>def</strong> odds(self):<br>        <strong>return</strong> skips(<br>            self.lower + (0 <strong>if</strong> (self.lower % 2) == 1 <strong>else</strong> 1),<br>            self.upper<br>        )</pre><p>The example below illustrates how an iterator returned by one of the methods in the definition of interval can be used.</p><pre>&gt;&gt;&gt; ns = interval(0, 10).odds()<br>&gt;&gt;&gt; <strong>while</strong> <strong>True</strong>: <em># Keep iterating and printing until exhaustion.</em><br><strong>...     try</strong>:<br>...         print(next(ns))<br>...     <strong>except</strong> StopIteration:<br>...         <strong>break<br>...<br></strong>1<br>3<br>5<br>7<br>9</pre><p>So far in this article, the distinction between <em>iterators</em> and <em>iterable data structures</em> has been explicit for clarity. However, the convention that is supported (and sometimes expected) throughout Python is that an iterable data structure has a <em>single</em> iterator that can be used to iterate over it. This iterator is returned by a special method <a href="https://docs.python.org/3/reference/datamodel.html#object.__iter__">__iter__</a> that is included in the class definition. In the example below, the interval class supports the creation of an iterator that visits every integer in the interval.</p><pre><strong>class</strong> every:<br>    <strong>def</strong> __init__(self, start, end):<br>        self.integer = start - 1<br>        self.end = end<br><br>    <strong>def</strong> __next__(self):<br>        self.integer += 1<br>        <strong>if</strong> self.integer &gt; self.end:<br>            <strong>raise</strong> StopIteration<br>        <strong>return</strong> self.integer<br><br><strong>class</strong> interval:<br>    <strong>def</strong> __init__(self, lower, upper):<br>        self.lower = lower<br>        self.upper = upper<br><br>    <strong>def</strong> __iter__(self):<br>        <strong>return</strong> every(self.lower, self.upper)</pre><p>Python’s built-in <a href="https://docs.python.org/3/library/functions.html#iter">iter</a> function can be used to invoke __iter__ for an instance of this data structure.</p><pre>&gt;&gt;&gt; ns = iter(interval(1, 3))<br>&gt;&gt;&gt; <strong>while</strong> <strong>True</strong>: <em># Keep iterating and printing until exhaustion.</em><br>...     <strong>try</strong>:<br>...         print(next(ns))<br>...     <strong>except</strong> StopIteration:<br>...         <strong>break<br>...<br></strong>1<br>2<br>3</pre><p>Including a definition for an __iter__ method also makes it possible to use many of Python&#39;s built-in functions and language constructs that expect an iterable data structure. This includes functions such as <a href="https://docs.python.org/3/library/functions.html#func-list">list</a> and <a href="https://docs.python.org/3/library/functions.html#func-set">set</a>, which use iter to obtain an iterator for their inputs.</p><pre>&gt;&gt;&gt; list(interval(0, 10))<br>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>&gt;&gt;&gt; set(interval(0, 10))<br>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}</pre><p>This also includes comprehensions and for loops.</p><pre>&gt;&gt;&gt;<strong> for</strong> n <strong>in</strong> interval(1, 4):<br>&gt;&gt;&gt;     print([k <strong>for</strong> k <strong>in</strong> interval(1, n)])<br>[1]<br>[1, 2]<br>[1, 2, 3]<br>[1, 2, 3, 4]</pre><p>There is nothing stopping you from making the iterator itself an iterable by having it return itself, as in the variant below.</p><pre><strong>class</strong> every:<br>    <strong>def</strong> __init__(self, start, end):<br>        self.integer = start - 1<br>        self.end = end<br><br>    <strong>def</strong> __next__(self):<br>        self.integer += 1<br>        <strong>if</strong> self.integer &gt; self.end:<br>            <strong>raise</strong> StopIteration<br>        <strong>return</strong> self.integer<br><br>    <strong>def</strong> __iter__(self):<br>        <strong>return</strong> self</pre><p>This approach ensures that there is no ambiguity (from a programmer’s perspective) about what will happen when built-in functions such as list are applied to an instance of the data structure.</p><pre>&gt;&gt;&gt; list(every(0, 10))<br>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><p>This practice is common and is the cause of some of the confusion and conflation that occurs between iterators and iterables. In addition to the potential for confusion, users of such a data structure must be careful to use the iterator as an iterable only once (or, alternatively, the object must reset its internal state every time __iter__ is invoked).</p><pre>&gt;&gt;&gt; ns = every(0, 10)<br>&gt;&gt;&gt; list(ns), list(ns) <em># Only returns contents the first time.</em><br>([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [])</pre><p>Nevertheless, this can also be a useful practice. Going back to the example with evens and odds, ensuring the iterators returned by these methods are also iterable means they can be fed directly into contexts that expect an iterable.</p><pre><strong>class</strong> skips:<br>    <strong>def</strong> __init__(self, start, end):<br>        self.integer = start - 2<br>        self.end = end<br><br>    <strong>def</strong> __next__(self):<br>        self.integer += 2<br>        <strong>if</strong> self.integer &gt; self.end:<br>            <strong>raise</strong> StopIteration<br>        <strong>return</strong> self.integer<br><br>    <strong>def</strong> __iter__(self):<br>        <strong>return</strong> self<br><br><strong>class</strong> interval:<br>    <strong>def</strong> __init__(self, lower, upper):<br>        self.lower = lower<br>        self.upper = upper<br><br>    <strong>def</strong> evens(self):<br>        <strong>return</strong> skips(<br>            self.lower + (0 <strong>if</strong> (self.lower % 2) == 0 <strong>else</strong> 1),<br>            self.upper<br>        )<br>    <br>    <strong>def</strong> odds(self):<br>        <strong>return</strong> skips(<br>            self.lower + (0 <strong>if</strong> (self.lower % 2) == 1 <strong>else</strong> 1),<br>            self.upper<br>        )</pre><p>The example below illustrates how this kind of interface can be used.</p><pre>&gt;&gt;&gt; i = interval(0, 10)<br>&gt;&gt;&gt; list(i.evens()), set(i.odds())<br>([0, 2, 4, 6, 8, 10], {1, 3, 5, 7, 9})</pre><h3>Generators</h3><p>Generators are data structures defined using either the yield statement or comprehension notation (also known as a <a href="https://docs.python.org/3/glossary.html#term-generator-expression">generator expression</a>). The example below defines a generator skips using both approaches.</p><pre><strong>def</strong> skips(start, end):<br>    integer = start<br>    <strong>while</strong> integer &lt;= end:<br>        <strong>yield</strong> integer<br>        integer += 2<br><br><strong>def</strong> skips(start, end):<br>    <strong>return</strong> (<br>        integer<br>        <strong>for</strong> integer <strong>in</strong> range(start, end)<br>        <strong>if</strong> (integer - start) % 2 == 0<br>    )</pre><p>When it is evaluated, a generator returns an iterator (more precisely called a <a href="https://docs.python.org/3/glossary.html#term-generator-iterator">generator iterator</a>). For example, as with any iterator, next can be applied directly to instances of this data structure.</p><pre>&gt;&gt;&gt; ns = skips(0, 10)<br>&gt;&gt;&gt; next(ns), next(ns), next(ns)<br>(0, 2, 4)</pre><p>As with any iterator, exhaustion can be detected by catching the StopIteration exception.</p><pre>&gt;&gt;&gt; ns = skips(0, 2)<br>&gt;&gt;&gt;<strong> try</strong>:<br>...     next(ns), next(ns), next(ns)<br>...<strong> except</strong> <strong>StopIteration</strong>:<br>...     print(&quot;Exhausted generator iterator.&quot;)<br>...<br>Exhausted generator iterator.</pre><p>Finally, an instance of the data structure can be used in any context that expects an iterable.</p><pre>&gt;&gt;&gt; list(skips(0, 10))<br>[0, 2, 4, 6, 8]</pre><p>It is possible to confirm that the result of evaluating skips is indeed a generator by checking its type.</p><pre>&gt;&gt;&gt;<strong> import</strong> types<br>&gt;&gt;&gt; isinstance(skips(0, 10), types.GeneratorType)<br><strong>True</strong></pre><p>It is also possible to inspect its type to confirm that skips indeed evaluates to an iterator.</p><pre>&gt;&gt;&gt; <strong>import</strong> collections<br>&gt;&gt;&gt; isinstance(skips(0, 10), collections.abc.Iterator)<br><strong>True</strong></pre><h3>Data Structures of Infinite or Unknown Size</h3><p>Among the use cases that demonstrate how iterators/generators serve as a powerful language feature are scenarios involving data structures whose size is unknown or unbounded/infinite (such as streams, very large files, databases, and so on). You have already seen that you can define an iterable that can produce new objects or values indefinitely, so iterables are an effective way to represent and encapsulate such structures.</p><p>Returning to the example described at the beginning of the article, recall that you are faced with creating a Python API for working with data streams that might (or might not) run out of items that can be drawn from them. The advantages of leveraging iterables and generators should be evident at this point, so suppose you move ahead with this option and implement an iterable to represent a data stream. How can you address the three specific requirements (<em>i.e.</em>, default/fall-back streams, interleaving, and splitting for parallelism) using these features?</p><p>To satisfy the first requirement, you must allow a user to exhaust one iterable and then switch to another one. This is straightforward to do by constructing a generator that concatenates two iterables.</p><pre><strong>def</strong> concatenate(xs, ys):<br>    <strong>for</strong> x <strong>in</strong> xs:<br>        <strong>yield</strong> x<br>    <strong>for</strong> y <strong>in</strong> ys:<br>        <strong>yield</strong> y</pre><p>Concatenating two instances of an iterable data structure is now straightforward.</p><pre>&gt;&gt;&gt; list(concatenate(skips(0,5), skips(6,11)))<br>[0, 2, 4, 6, 8, 10]</pre><p>Notice that if the first iterable is never exhausted, the second one will never be used.</p><p>To address the second requirement, first consider a simpler scenario. What if you would like to “line up” or “pair up” entries in two or more iterables? You can use the built-in <a href="https://docs.python.org/3/library/functions.html#zip">zip</a> function.</p><pre>&gt;&gt;&gt; list(zip(skips(0,5), skips(6,11)))<br>[(0, 6), (2, 8), (4, 10)]</pre><p>Notice that the result of evaluating zip is indeed an iterator.</p><pre>&gt;&gt;&gt;<strong> import</strong> collections<br>&gt;&gt;&gt; isinstance(<br>...     zip(skips(0,5), skips(6,11)),<br>...     collections.abc.Iterator<br>... )<br>...<br><strong>True</strong></pre><p>Combining zip with comprehension syntax, you can now define a generator that <em>interleaves</em> two iterables (switching back and forth between emitting an item from one and then the other).</p><pre><strong>def</strong> interleave(xs, ys):<br>    <strong>return</strong> (<br>        z <br>        <strong>for</strong> (x, y) <strong>in</strong> zip(xs, ys) <br>        <strong>for</strong> z <strong>in</strong> (x, y)<br>    )</pre><p>As with concatenation, interleaving is now concise and straightforward.</p><pre>&gt;&gt;&gt; list(interleave(skips(0,5), skips(6,11)))<br>[0, 6, 2, 8, 4, 10]</pre><p>Finally, how can you help users process items from a stream in parallel? Because you are already using iterables, users have some options available to them from the built-in <a href="https://docs.python.org/3/library/itertools.html">itertools</a> library.</p><p>One option is <a href="https://docs.python.org/3/library/itertools.html#itertools.islice">islice</a>, which behaves in a similar manner to Python <a href="https://docs.python.org/3/library/functions.html?highlight=slice#slice">slice notation</a> (such as xs[0:10] to extract the first ten entries from a list xs). Users can use this function to extract items in batches and (1) pass each item in a batch to its own separate thread or (2) pass batches of items to separate threads. A basic batching method is presented below.</p><pre><strong>def</strong> batch(xs, size):<br>    <strong>from</strong> itertools<strong> import</strong> islice<br>    ys = list(islice(xs, 0, size))<br>    <strong>while</strong> len(ys) &gt; 0:<br>        <strong>yield</strong> ys<br>        ys = list(islice(xs, 0, size))</pre><p>Notice that this method inherits the graceful behavior of slice notation when the boundaries of the slices do not line up exactly with the number entries in the data structure instance.</p><pre>&gt;&gt;&gt; list(batch(skips(0,21), 3))<br>[[0, 2, 4], [6, 8, 10], [12, 14, 16], [18, 20]]</pre><p>Can you define a generator that returns batches of batches (<em>e.g.</em>, at most n batches each of size at most k)?</p><p>Another option is to use the <a href="https://docs.python.org/3/library/itertools.html#itertools.tee">tee</a> function, which can duplicate a single iterable into multiple iterables. However, this function is really only simulating this effect by storing a large amount of auxiliary information from one of the iterables. Thus, it may use a significant amount of memory and is not safe to use with multiprocessing. It is best suited for situations in which the iterables are known to have a small number of items, as in the example below.</p><pre>&gt;&gt;&gt;<strong> from</strong> itertools <strong>import</strong> tee<br>&gt;&gt;&gt; (a, b) = tee(skips(0,11), 2)<br>&gt;&gt;&gt; (list(a), list(b))<br>([0, 2, 4, 6, 8, 10], [0, 2, 4, 6, 8, 10])</pre><p>The example above is arguably implemented in a more clear and familiar way by simply wrapping the iterables using list.</p><pre>&gt;&gt;&gt; ns = list(skips(0,11))<br>&gt;&gt;&gt; (ns, ns)<br>([0, 2, 4, 6, 8, 10], [0, 2, 4, 6, 8, 10])</pre><h3>Further Reading</h3><p>This article presents the relationships and distinctions between a number of related Python language constructs, and illustrates via the use case of data streams how these constructs can be leveraged. You can visit the Python Wiki if you are looking for additional discussion and examples of both <a href="https://wiki.python.org/moin/Iterator">iterators</a> and <a href="https://wiki.python.org/moin/Generators">generators</a>. The Python documentation also contains a <a href="https://docs.python.org/3/howto/functional.html">Functional Programming HOWTO</a> that discusses how iterators and generators offer new kinds of modularity and composability. Furthermore, the Python documentation entry for the built-in <a href="https://docs.python.org/3/library/itertools.html">itertools</a> library contains many built-in functions and recommended patterns that are specialized to particular scenarios.</p><p><em>This article is also available as a </em><a href="https://github.com/python-supply/iterators-generators-and-uncertainty/blob/master/iterators-generators-and-uncertainty.ipynb"><em>Jupyter Notebook</em></a><em> and in </em><a href="https://python.supply/iterators-generators-and-uncertainty"><em>HTML</em></a><em> form on </em><a href="https://github.com/python-supply"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e7f85183b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-supply/iterators-generators-and-uncertainty-a3e7f85183b">Iterators, Generators, and Uncertainty</a> was originally published in <a href="https://medium.com/python-supply">Python Supply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>