<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Stanislas Morbieu - Python</title><link href="https://smorbieu.gitlab.io/" rel="alternate"></link><link href="https://smorbieu.gitlab.io/feeds/tag_python.atom.xml" rel="self"></link><id>https://smorbieu.gitlab.io/</id><updated>2019-06-17T10:00:00+02:00</updated><entry><title>AI Paris 2019 in one picture</title><link href="https://smorbieu.gitlab.io/ai-paris-2019-in-one-picture" rel="alternate"></link><published>2019-06-17T10:00:00+02:00</published><updated>2019-06-17T10:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2019-06-17:/ai-paris-2019-in-one-picture</id><summary type="html">&lt;p class="first last"&gt;This week, I was at the AI Paris 2019 event to represent &lt;a class="reference external" href="https://www.kernix.com"&gt;Kernix&lt;/a&gt;. We had great talks with so many people, and I barely had time to go around to look what other companies were working on. That is why I look at this afterwards. Can we have a big picture of the event without being there?&lt;/p&gt;
</summary><content type="html">&lt;p&gt;Last week, I was at the AI Paris 2019 event to represent &lt;a class="reference external" href="https://www.kernix.com"&gt;Kernix&lt;/a&gt;.
We had great talks with so many people, and
I barely had time to go around to look what other companies were working on.
That is why I look at this afterwards. Can we have a big picture of the event without being there?&lt;/p&gt;
&lt;p&gt;It happens that the list of the companies is on the &lt;a class="reference external" href="https://aiparis.fr/2019/"&gt;website of the AI Paris 2019&lt;/a&gt;.
With a little bit of Python code we can retrieve it.
The following Python code retrieves the html content of the page we are interested in:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;urllib&lt;/span&gt;


&lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"https://aiparis.fr/2019/sponsors-et-exposants/"&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;urllib&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;urlopen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;html&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;read&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'utf-8'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Note that &lt;tt class="docutils literal"&gt;response.read()&lt;/tt&gt; returns bytes, so we have to decode it to get a string. The encoding used is utf-8, which
can be seen in the &lt;tt class="docutils literal"&gt;charset&lt;/tt&gt; attribute of the &lt;tt class="docutils literal"&gt;meta&lt;/tt&gt; tag (and fortunately it is the correct encoding, which is not always the case).
Looking at the html, we can notice that the data is in a javascript variable. Let's get the line where it is defined:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;re&lt;/span&gt;


&lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;".*Kernix.*"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;html&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;By default, the regex does not span multiple lines.
The &lt;tt class="docutils literal"&gt;line&lt;/tt&gt; variable is almost a json. We can get the data as a Python dictionary with the following:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;json&lt;/span&gt;


&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'['&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'{"all":'&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s1"&gt;'}'&lt;/span&gt;
&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Let's now get the descriptions of the companies concatenated into a single string:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;re&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;clean_html&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;html&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;regex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;compile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'&amp;lt;.*?&amp;gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;re&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sub&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;regex&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;html&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;

&lt;span class="n"&gt;corpus&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;clean_html&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'description'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'all'&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;" "&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;corpus&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;tt class="docutils literal"&gt;clean_html&lt;/tt&gt; function is created since the descriptions contain html code and removing the tags make it more readable.
A way to go when dealing with text is to remove "stopwords", &lt;em&gt;i.e.&lt;/em&gt; words that do not contain meaningfull information:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;nltk.corpus&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;stopwords&lt;/span&gt;


&lt;span class="n"&gt;stop_words&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stopwords&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'french'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
              &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'le'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'leur'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'afin'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'les'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'leurs'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
              &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stopwords&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'english'&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;a class="reference external" href="https://www.nltk.org/"&gt;NLTK library&lt;/a&gt; provides lists of stopwords. We use both the english and french lists since the content is mosly written in french, but some descriptions are in english.
I added some french stopwords.&lt;/p&gt;
&lt;p&gt;I am not a big fan of word clouds since we can only spot quickly a few words, but for this use case, we can get a pretty good big picture in very few lines:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="AI Paris 2019 word cloud" src="https://smorbieu.gitlab.io/images/aiparis2019.png"/&gt;
&lt;/div&gt;
&lt;p&gt;Here is the code to generate it:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;random&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nn"&gt;plt&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;wordcloud&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;WordCloud&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;grey_color_func&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;font_size&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;position&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;orientation&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;random_state&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"hsl(0, 0&lt;/span&gt;&lt;span class="si"&gt;%%&lt;/span&gt;&lt;span class="s2"&gt;, &lt;/span&gt;&lt;span class="si"&gt;%d%%&lt;/span&gt;&lt;span class="s2"&gt;)"&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;randint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="n"&gt;wordcloud&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;WordCloud&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;width&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;height&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;800&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="n"&gt;background_color&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"black"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="n"&gt;stopwords&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;stop_words&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="n"&gt;random_state&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="n"&gt;color_func&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;grey_color_func&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;generate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;fig&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;figure&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;figsize&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;imshow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wordcloud&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;interpolation&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"bilinear"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;axis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"off"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tight_layout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pad&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;fig&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;savefig&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'wordcloud.png'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dpi&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;fig&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dpi&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;show&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;tt class="docutils literal"&gt;grey_color_func&lt;/tt&gt; function enable a greyscale picture.
A fixed random state enables reproductibility.
Setting both the &lt;tt class="docutils literal"&gt;width&lt;/tt&gt;, &lt;tt class="docutils literal"&gt;height&lt;/tt&gt; and the &lt;tt class="docutils literal"&gt;figsize&lt;/tt&gt; enable a high quality output.
The margins are removed with the two lines:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;axis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"off"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tight_layout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pad&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Let's get back to the word cloud.
We can spot immediately the words "solution"
(it is the same in french and english),
"data" (both in french "donnée" and english "data") and
"company" ("entreprise" in french).
The expressions "AI" ("IA" in french) and "artificial intelligence" ("intelligence artificielle")
come only later which is quite surprising for an event focusing on artificial intelligence as a whole.
In fact, AI is often seen as a solution to use data in an useful way.&lt;/p&gt;
&lt;p&gt;Many actors are working on how to store data, manage and process it (which is very important), but only a few, from what I saw and heard, focus on creating value for people.
I am always delighted to create something useful for people in they day-to-day life, whether it is a recommender system to discover things we never thought exist, or automate boring tasks,
improve research in the pharmaceutical sector, and so many others. AI is about people!&lt;/p&gt;
</content><category term="Python"></category></entry><entry><title>Accuracy: from classification to clustering evaluation</title><link href="https://smorbieu.gitlab.io/accuracy-from-classification-to-clustering-evaluation" rel="alternate"></link><published>2019-06-04T08:00:00+02:00</published><updated>2019-06-04T08:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2019-06-04:/accuracy-from-classification-to-clustering-evaluation</id><summary type="html">&lt;p class="first last"&gt;Accuracy is often used to measure the quality of a classification. It is also used for clustering. However, the &lt;a class="reference external" href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"&gt;scikit-learn accuracy_score function&lt;/a&gt; only provides a lower bound of accuracy for clustering. This blog post explains how accuracy should be computed for clustering.&lt;/p&gt;
</summary><content type="html">
&lt;p&gt;Accuracy is often used to measure the quality of a classification. It is also used for clustering.
However, the &lt;a class="reference external" href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"&gt;scikit-learn accuracy_score function&lt;/a&gt; only provides a lower bound of accuracy for clustering.
This blog post explains how accuracy should be computed for clustering.&lt;/p&gt;
&lt;p&gt;Let's first recap what accuracy is for a classification task.&lt;/p&gt;
&lt;div class="section" id="accuracy-for-classification"&gt;
&lt;h2&gt;Accuracy for classification&lt;/h2&gt;
&lt;p&gt;For &lt;span class="math"&gt;\(n\)&lt;/span&gt; samples in a dataset, let &lt;span class="math"&gt;\(y_i\)&lt;/span&gt; be the class label for the &lt;span class="math"&gt;\(i\)&lt;/span&gt;-th sample and &lt;span class="math"&gt;\(\hat{y}_i\)&lt;/span&gt; the predicted value.
Accuracy between the class labels &lt;span class="math"&gt;\(y\)&lt;/span&gt; and the predicted values &lt;span class="math"&gt;\(\hat{y}\)&lt;/span&gt; is defined by:&lt;/p&gt;
&lt;div class="math"&gt;
\begin{equation*}
accuracy(y, \hat{y}) = \frac{1}{n} \sum_{i=0}^{n-1} 1(\hat{y}_i = y_i)
\end{equation*}
&lt;/div&gt;
&lt;p&gt;where &lt;span class="math"&gt;\(x \rightarrow 1(x)\)&lt;/span&gt; is the indicator function:
&lt;span class="math"&gt;\(1(\hat{y}_i = y_i) = 1\)&lt;/span&gt; if &lt;span class="math"&gt;\(\hat{y}_i = y_i\)&lt;/span&gt; and &lt;span class="math"&gt;\(0\)&lt;/span&gt; else.&lt;/p&gt;
&lt;p&gt;It is computed as the sum of the diagonal elements of the confusion matrix, divided by the number of samples to get a value between 0 and 1.&lt;/p&gt;
&lt;p&gt;For clustering, there is however no association provided by the clustering algorithm between the class labels and the predicted cluster labels. We therefore need to change the formula a little.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="accuracy-for-clustering"&gt;
&lt;h2&gt;Accuracy for clustering&lt;/h2&gt;
&lt;p&gt;For clustering, we have to find the best match between the class labels and the cluster labels, so accuracy is defined by:&lt;/p&gt;
&lt;div class="math"&gt;
\begin{equation*}
accuracy(y, \hat{y}) = \max_{perm \in P} \frac{1}{n} \sum_{i=0}^{n-1} 1(perm(\hat{y}_i) = y_i)
\end{equation*}
&lt;/div&gt;
&lt;p&gt;where &lt;span class="math"&gt;\(P\)&lt;/span&gt; is the set of all permutations in &lt;span class="math"&gt;\([1; K]\)&lt;/span&gt; where &lt;span class="math"&gt;\(K\)&lt;/span&gt; is the number of clusters.&lt;/p&gt;
&lt;p&gt;It is important to note that there are &lt;span class="math"&gt;\(K !\)&lt;/span&gt; permutations in &lt;span class="math"&gt;\(P\)&lt;/span&gt; which is quite high and the computation of accuracy is therefore prohibitive if we apply blindly this formula.
The &lt;a class="reference external" href="https://en.wikipedia.org/wiki/Hungarian_algorithm"&gt;Hungarian algorithm&lt;/a&gt; can help us compute it in &lt;span class="math"&gt;\(O(K^3)\)&lt;/span&gt; which is significantly faster.&lt;/p&gt;
&lt;p&gt;Let's see in practice how to compute accuracy on clustering results in a polynomial time.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="hands-on"&gt;
&lt;h2&gt;Hands-on&lt;/h2&gt;
&lt;p&gt;In this part, we are going to first get some textual data to process, then cluster the documents and compute the accaracy between the clustering results and the known classes.&lt;/p&gt;
&lt;div class="section" id="get-some-data"&gt;
&lt;h3&gt;Get some data&lt;/h3&gt;
&lt;p&gt;Let's get some documents from the &lt;a class="reference external" href="http://qwone.com/~jason/20Newsgroups/"&gt;20 Newsroups data set&lt;/a&gt;. We retrieve only five classes from it:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.datasets&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;fetch_20newsgroups&lt;/span&gt;

&lt;span class="n"&gt;categories&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="s1"&gt;'rec.motorcycles'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'rec.sport.baseball'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'comp.graphics'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'sci.space'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'talk.politics.mideast'&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;ng5&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fetch_20newsgroups&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;categories&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;shuffle&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;labels&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ng5&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt;
&lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ng5&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;a class="reference external" href="https://en.wikipedia.org/wiki/Latent_semantic_analysis"&gt;Latent Semantic Indexing&lt;/a&gt; is a well known method to transform documents into low dimensional vectors (low compared to the size of the vocabulary, &lt;em&gt;i.e.&lt;/em&gt; the number of unique words in the dataset):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.pipeline&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Pipeline&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.feature_extraction.text&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;CountVectorizer&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.feature_extraction.text&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;TfidfTransformer&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.decomposition&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;TruncatedSVD&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.preprocessing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Normalizer&lt;/span&gt;

&lt;span class="n"&gt;pipeline&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Pipeline&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'vect'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;CountVectorizer&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'tfidf'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;TfidfTransformer&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'svd'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;TruncatedSVD&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'normalizer'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Normalizer&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="n"&gt;pipeline&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;set_params&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;svd__n_components&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pipeline&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fit_transform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Each line of the matrix &lt;tt class="docutils literal"&gt;A&lt;/tt&gt; is a document represented by a vector. We can therefore apply a clustering algorithm on this matrix.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="clustering"&gt;
&lt;h3&gt;Clustering&lt;/h3&gt;
&lt;p&gt;Spherical k-means is a good algorithm to cluster textual data. One implementation is given by the &lt;a class="reference external" href="https://coclust.readthedocs.io"&gt;Coclust Python library&lt;/a&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;coclust.clustering&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;SphericalKmeans&lt;/span&gt;

&lt;span class="n"&gt;skm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;SphericalKmeans&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n_clusters&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;skm&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;A&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;predicted_labels&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;skm&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;labels_&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We are now ready to compute the accuracy between &lt;tt class="docutils literal"&gt;labels&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;predicted_labels&lt;/tt&gt;. As described before, we can do this by first computing the confusion matrix.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="confusion-matrix"&gt;
&lt;h3&gt;Confusion matrix&lt;/h3&gt;
&lt;p&gt;Scikit-learn library provides a function called &lt;a class="reference external" href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html"&gt;confusion_matrix&lt;/a&gt; to create a
&lt;a class="reference external" href="https://smorbieu.gitlab.io/dense-matrices-implementation-in-python"&gt;Numpy array&lt;/a&gt; containing the values of the confusion matrix:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.metrics&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;confusion_matrix&lt;/span&gt;

&lt;span class="n"&gt;cm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;confusion_matrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;labels&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;predicted_labels&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Let's visualize it with &lt;a class="reference external" href="https://seaborn.pydata.org/"&gt;Seaborn visualization library&lt;/a&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;seaborn&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nn"&gt;sns&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;sns&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="n"&gt;ax&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sns&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heatmap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;annot&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fmt&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"d"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cmap&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Blues"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;div class="figure"&gt;
&lt;img alt="Confusion matrix" src="https://smorbieu.gitlab.io/images/clustering/cm.svg"/&gt;
&lt;/div&gt;
&lt;p&gt;To compute the accuracy, one need to sum the values on the diagonal, but for clustering the rows (or columns) of the confusion matrix should be permuted to obtain the maximum value for the sum. This is not the case here. Let's see how to find the best permutation.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="permutation-maximizing-the-sum-of-the-diagonal-elements"&gt;
&lt;h3&gt;Permutation maximizing the sum of the diagonal elements&lt;/h3&gt;
&lt;p&gt;Scikit-learn provides a function &lt;a class="reference external" href="https://github.com/scikit-learn/scikit-learn/blob/3cb0b3bc22b0a6f99f80c025fd378660896a2c68/sklearn/utils/linear_assignment_.py#L19-L60"&gt;linear_assignment&lt;/a&gt; to apply the Hungarian algorithm. One can use it to create our reordered confusion matrix &lt;tt class="docutils literal"&gt;cm2&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.utils.linear_assignment_&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;linear_assignment&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;numpy&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nn"&gt;np&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_make_cost_m&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;cm&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;indexes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;linear_assignment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_make_cost_m&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="n"&gt;js&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;indexes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])]&lt;/span&gt;
&lt;span class="n"&gt;cm2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;[:,&lt;/span&gt; &lt;span class="n"&gt;js&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Since &lt;tt class="docutils literal"&gt;linear_assigment&lt;/tt&gt; minimizes a cost which should be positive, we defined the function &lt;tt class="docutils literal"&gt;_make_cost_m&lt;/tt&gt; to transform the confusion matrix into a cost matrix. The reordered confusion matrix &lt;tt class="docutils literal"&gt;cm2&lt;/tt&gt; can be visualized:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Reordered confusion matrix" src="https://smorbieu.gitlab.io/images/clustering/cm2.svg"/&gt;
&lt;/div&gt;
&lt;p&gt;We are almost done. Let's finally compute the accuracy.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="compute-accuracy"&gt;
&lt;h3&gt;Compute accuracy&lt;/h3&gt;
&lt;p&gt;The accuracy is the sum of the diagonal elements divided by the number of samples:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Instead of implementing all this stuff ourselves, we could just use &lt;tt class="docutils literal"&gt;accuracy&lt;/tt&gt; function provided by Coclust:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;coclust.evaluation.external&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;accuracy&lt;/span&gt;

&lt;span class="n"&gt;accuracy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;labels&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;predicted_labels&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It should be noted that scikit-learn &lt;tt class="docutils literal"&gt;accuracy_score&lt;/tt&gt; function does not give the accuracy score for the clustering since it does not permute the rows of the confusion matrix:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;sklearn.metrics.classification&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;accuracy_score&lt;/span&gt;

&lt;span class="n"&gt;accuracy_score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;labels&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;predicted_labels&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;gives the same value as:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cm&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="take-away"&gt;
&lt;h2&gt;Take away&lt;/h2&gt;
&lt;p&gt;Here is a summary of the key elements of this post:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;accuracy_score&lt;/tt&gt; provided by scikit-learn is meant to deal with classification results, not clustering.&lt;/li&gt;
&lt;li&gt;Computing accuracy for clustering can be done by reordering the rows (or columns) of the confusion matrix so that the sum of the diagonal values is maximal.&lt;/li&gt;
&lt;li&gt;The linear assignment problem can be solved in &lt;span class="math"&gt;\(O(n^3)\)&lt;/span&gt; instead of &lt;span class="math"&gt;\(O(n!)\)&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a class="reference external" href="https://coclust.readthedocs.io"&gt;Coclust library&lt;/a&gt; provides an implementation of the accuracy for clustering results.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;script type='text/javascript'&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="evaluation measure"></category><category term="clustering"></category><category term="Python"></category></entry><entry><title>Dense matrices implementation in Python</title><link href="https://smorbieu.gitlab.io/dense-matrices-implementation-in-python" rel="alternate"></link><published>2019-02-04T20:00:00+01:00</published><updated>2019-02-04T20:00:00+01:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2019-02-04:/dense-matrices-implementation-in-python</id><summary type="html">&lt;p class="first last"&gt;Machine learning algorithms often use matrices to store data and compute operations such as multiplications or singular value decomposition. The purpose of this article is to see how matrices are implemented in Python: how the data is stored and how much memory it consumes.&lt;/p&gt;
</summary><content type="html">
&lt;!-- :series: implementation of matrices --&gt;
&lt;p&gt;Machine learning algorithms often use matrices to store data and compute operations such as multiplications or singular value decomposition. The purpose of this article is to see how matrices are implemented in Python: how the data is stored and how much memory it consumes.&lt;/p&gt;
&lt;!-- The computational side will be exposed in another post. --&gt;
&lt;p&gt;Numpy and SciPy are two major libraries which provide repectivelely dense and sparse implementations. Both rely on Numpy ndarrays, so it is important to first look at how ndarrays are implemented. We will then compare this implementation (on the storage aspect only) to implementations in Python without external library. Last, we will see what Numpy dense matrices are compared to ndarrays.&lt;/p&gt;
&lt;div class="section" id="internals-of-a-numpy-ndarray"&gt;
&lt;h2&gt;Internals of a Numpy ndarray&lt;/h2&gt;
&lt;p&gt;Numpy is a &lt;a class="reference external" href="https://docs.python.org/3/extending/"&gt;C extension&lt;/a&gt; Python library. It therefore provides &lt;a class="reference external" href="https://docs.scipy.org/doc/numpy/reference/c-api.types-and-structures.html"&gt;C API and code&lt;/a&gt; which will help us understand how data is stored. For instance, in C, every ndarray is a pointer to a &lt;a class="reference external" href="https://docs.scipy.org/doc/numpy/reference/c-api.types-and-structures.html#c.PyArrayObject"&gt;PyArrayObject&lt;/a&gt; C structure. This structure is defined as follows:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;PyArrayObject&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;PyObject_HEAD&lt;/span&gt;
    &lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;nd&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;npy_intp&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;dimensions&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;npy_intp&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;strides&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;PyObject&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;PyArray_Descr&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;descr&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;flags&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;PyObject&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;weakreflist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;PyArrayObject&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;a class="reference external" href="https://github.com/numpy/numpy/blob/master/numpy/core/include/numpy/ndarraytypes.h#L658-L724"&gt;PyArrayObject implementation&lt;/a&gt; helps us better understand what the fields are used for:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;&lt;a class="reference external" href="https://docs.python.org/dev/c-api/structures.html#c.PyObject_HEAD"&gt;PyObject_HEAD&lt;/a&gt; is a macro used for Python internal use.&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;data&lt;/tt&gt; is a pointer to the raw data buffer, &lt;em&gt;i.e.&lt;/em&gt; the values contained in the array&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;nd&lt;/tt&gt; is the number of dimensions&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;dimensions&lt;/tt&gt; is the size in each dimension, &lt;em&gt;i.e.&lt;/em&gt; the shape of the array&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;a.strides&lt;/tt&gt; gives how far in bytes it has to step, for each dimension, to get to the next element of the array (next row, or next column)&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;base&lt;/tt&gt; is a pointer to the original array in the case of a view&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;descr&lt;/tt&gt; is a pointer to the type of the elements stored in the array&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;flags&lt;/tt&gt; gives information about how the array is stored in memory&lt;/li&gt;
&lt;li&gt;&lt;tt class="docutils literal"&gt;weakreflist&lt;/tt&gt; is a used for weak references&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's consider an example of an ndarray to explain with more details the fields:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="p"&gt;([[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
              &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We will first look at the &lt;tt class="docutils literal"&gt;nd&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;dimensions&lt;/tt&gt; fields which give general informations about the shape of the ndarray. Then we will see how the elements of the array are stored. References (&lt;tt class="docutils literal"&gt;base&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;weakreflist&lt;/tt&gt; fields) are discussed later. Last, the PyObject_HEAD field is presented.&lt;/p&gt;
&lt;div class="section" id="shape-of-the-ndarray"&gt;
&lt;h3&gt;Shape of the ndarray&lt;/h3&gt;
&lt;p&gt;The number of dimensions (&lt;tt class="docutils literal"&gt;nd&lt;/tt&gt; in C) is obtained in Python with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ndim&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which outputs &lt;tt class="docutils literal"&gt;2&lt;/tt&gt;. The dimensions are the rows and the columns in this case.
The size of the array in each dimension (&lt;tt class="docutils literal"&gt;dimensions&lt;/tt&gt; in C) is obtained in Python with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which outputs &lt;tt class="docutils literal"&gt;(2, 3)&lt;/tt&gt;. It corresponds to the number of rows and the number of columns respectively.
These two fields (&lt;tt class="docutils literal"&gt;ndim&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;shape&lt;/tt&gt;) can be changed independently of the elements of the array. For instance, if we consider a one dimensional array &lt;tt class="docutils literal"&gt;x&lt;/tt&gt; and an array &lt;tt class="docutils literal"&gt;y&lt;/tt&gt; of shape &lt;tt class="docutils literal"&gt;(3, 2)&lt;/tt&gt; with the same elements:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reshape&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;their data is the same:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tobytes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tobytes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tobytes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;evaluates to &lt;tt class="docutils literal"&gt;True&lt;/tt&gt;.
Let's get deeper to see how the data is stored.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="how-is-the-data-stored"&gt;
&lt;h3&gt;How is the data stored?&lt;/h3&gt;
&lt;p&gt;The data is stored in &lt;tt class="docutils literal"&gt;a.data&lt;/tt&gt;. Let's set &lt;tt class="docutils literal"&gt;b = a.data.tobytes()&lt;/tt&gt;.
The value &lt;tt class="docutils literal"&gt;a.itemsize&lt;/tt&gt; gives the number of bytes used to store one element of the array.
The value returned by &lt;tt class="docutils literal"&gt;len(b)&lt;/tt&gt; is &lt;tt class="docutils literal"&gt;48&lt;/tt&gt; which corresponds to the number of bytes &lt;tt class="docutils literal"&gt;a.nbytes&lt;/tt&gt; and also to the product of &lt;tt class="docutils literal"&gt;a.itemsize&lt;/tt&gt; (8) and the number of elements (6).
The number of bytes used to store one element of the array depends on the type of the elements.&lt;/p&gt;
&lt;div class="section" id="types-of-the-elements"&gt;
&lt;h4&gt;Types of the elements&lt;/h4&gt;
&lt;p&gt;We can see the type used (&lt;tt class="docutils literal"&gt;descr&lt;/tt&gt; in C) with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dtype&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which outputs &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;dtype('int64')&lt;/span&gt;&lt;/tt&gt;. It means that the elements are ints stored with 64 bits each.
We can change this type, and then see data as bytes with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;astype&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'int16'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tobytes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00'&lt;/span&gt;&lt;/tt&gt;.
Here, &lt;tt class="docutils literal"&gt;\x01&lt;/tt&gt; is the hexadecimal string representation of the bits contained in one byte: for instance 0 is represented by &lt;tt class="docutils literal"&gt;\x00&lt;/tt&gt; and 255 is represented by &lt;tt class="docutils literal"&gt;\xff&lt;/tt&gt; (we can store &lt;span class="math"&gt;\(256 = 2^8\)&lt;/span&gt; values in one byte).
Since the values are now stored with 16 bits, &lt;em&gt;i.e.&lt;/em&gt; 2 bytes, we can retrieve the first two elements of the array (1 and 2) with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="s1"&gt;'little'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;from_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="s1"&gt;'little'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Two questions arise:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;What does &lt;tt class="docutils literal"&gt;little&lt;/tt&gt; mean?&lt;/li&gt;
&lt;li&gt;And why is 2 the second element and not 4?&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class="section" id="little-endian-or-big-endian"&gt;
&lt;h4&gt;Little endian or big endian&lt;/h4&gt;
&lt;p&gt;Here, &lt;tt class="docutils literal"&gt;little&lt;/tt&gt; corresponds to &lt;a class="reference external" href="https://en.wikipedia.org/wiki/Endianness#Little"&gt;little-endian&lt;/a&gt;. It means that we read the bytes from left to right to get the number represented.
If instead we want the data to be stored in big-endian, we can change it and see the data with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;astype&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'&amp;gt;i2'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tobytes&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It now outputs &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;b'\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06'&lt;/span&gt;&lt;/tt&gt;. Note here that each pair of bytes (corresponding to one element of the array) is inverted.
We can read the array without changing the data but reading it as if it were stored in little-endian:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;newbyteorder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'&amp;lt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;array&lt;/span&gt;&lt;span class="p"&gt;([[&lt;/span&gt; &lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="mi"&gt;512&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="mi"&gt;768&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
       &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1024&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1280&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1536&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;int16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Let's understand what happened by looking at each element of the array (&lt;em&gt;i.e.&lt;/em&gt; two bytes). With big-endian:&lt;/p&gt;
&lt;table class="docutils"&gt;

&lt;thead&gt;
&lt;tr&gt;&lt;th class="head"&gt;bytes in hexadecimal&lt;/th&gt;
&lt;th class="head"&gt;number (big-endian)&lt;/th&gt;
&lt;th class="head"&gt;bits&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x01&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^0 = 1\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000001&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x02&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^1 = 2\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000010&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x03&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^0 + 2^1 = 3\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000011&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x04&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^2 = 4\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000100&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x05&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^2 + 2^0 = 5\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000101&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x06&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^2 + 2^1 = 6\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000000 00000110&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;In this table, we wrote the least significant bit on the right (&lt;em&gt;i.e.&lt;/em&gt; if this bit is 1 then it corresponds to &lt;span class="math"&gt;\(2^0\)&lt;/span&gt; in the decomposition, the second from the right corresponds to &lt;span class="math"&gt;\(2^1\)&lt;/span&gt; and so on). In big-endian, the bytes are read from right to left.
If instead we read the same bytes in little-endian (&lt;em&gt;i.e.&lt;/em&gt; the least important byte is on the left), we have the following numbers:&lt;/p&gt;
&lt;table class="docutils"&gt;

&lt;thead&gt;
&lt;tr&gt;&lt;th class="head"&gt;bytes in hexadecimal&lt;/th&gt;
&lt;th class="head"&gt;number (little-endian)&lt;/th&gt;
&lt;th class="head"&gt;bits (bytes are reodered)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x01&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^8 = 256\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000001 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x02&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^9 = 512\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000010 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x03&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^8 + 2^9 = 768\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000011 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x04&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^{10} = 1024\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000100 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x05&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^8 + 2^{10} = 1280\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000101 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;\x00 \x06&lt;/td&gt;
&lt;td&gt;&lt;span class="math"&gt;\(2^9 + 2^{10} = 1536\)&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;00000110 00000000&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Note that we inverted the order of the bytes but not all the bits as a whole: for &lt;tt class="docutils literal"&gt;\x00\x01&lt;/tt&gt; we get &lt;tt class="docutils literal"&gt;00000001 00000000&lt;/tt&gt; in little-endian and not &lt;tt class="docutils literal"&gt;10000000 00000000&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;We saw how each element is stored individually. Let's see why the second element in the data buffer is 2 (first row and second column) and not 4 (first column and second row).&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="column-major-or-row-major"&gt;
&lt;h4&gt;Column major or row major&lt;/h4&gt;
&lt;p&gt;The second element is 2 because the rows are considered to be laid out as contiguous blocks: 1, 2, 3, 4, 5, 6 (the first row is 1, 2, 3 which are contiguous and the second row is 4, 5, 6). We name it "row major" or "C-style contiguous".
The &lt;a class="reference external" href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html"&gt;flags&lt;/a&gt;
property (&lt;tt class="docutils literal"&gt;a.flags&lt;/tt&gt;) gives us how the data is actually stored in memory:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;C_CONTIGUOUS&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;F_CONTIGUOUS&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="n"&gt;OWNDATA&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;WRITEABLE&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;ALIGNED&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;WRITEBACKIFCOPY&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="n"&gt;UPDATEIFCOPY&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In this case the data is stored in C-style. We can also store it as contiguous blocks of columns, called "Fortran-style contiguous" or "column major" with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;asfortranarray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The flags changed:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;C_CONTIGUOUS&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="n"&gt;F_CONTIGUOUS&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;OWNDATA&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;WRITEABLE&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;ALIGNED&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;WRITEBACKIFCOPY&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="n"&gt;UPDATEIFCOPY&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;but the data didn't: &lt;tt class="docutils literal"&gt;a.data == y.data&lt;/tt&gt; returns &lt;tt class="docutils literal"&gt;True&lt;/tt&gt;. The data array is still indexed as C-style, even if the underlying data is stored in memory as Fortran-style. This unables to manipulate the array the same way independently of how it is stored in memory.
Storing it as row major or column major influences on the efficiency of the operations on the array: for C contiguous memory layout, operations such as &lt;tt class="docutils literal"&gt;a.sum(axis=1)&lt;/tt&gt; (sums the rows) are usually faster than column-wise operations since they access memory addresses which are next to each other. &lt;tt class="docutils literal"&gt;a.strides&lt;/tt&gt; gives us how far in bytes it has to step to get to the next value, repectively for the next row and the next column. Here it is &lt;tt class="docutils literal"&gt;(6, 2)&lt;/tt&gt; for C-style and &lt;tt class="docutils literal"&gt;(2, 4)&lt;/tt&gt; for Fortran-style.&lt;/p&gt;
&lt;p&gt;We saw how each data element is stored and how elements are laid out along with the different fields in the C structure and in Python to get this information. Let's move on to references.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="references"&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;p&gt;When we create a view on an array, the data is not copied, a reference to the underlying data is stored. For instance, if we set the variable &lt;tt class="docutils literal"&gt;c&lt;/tt&gt; as the two last colums of the array &lt;tt class="docutils literal"&gt;a&lt;/tt&gt; with &lt;tt class="docutils literal"&gt;c = &lt;span class="pre"&gt;a[:;&lt;/span&gt; &lt;span class="pre"&gt;-2:]&lt;/span&gt;&lt;/tt&gt;, we can access the array &lt;tt class="docutils literal"&gt;a&lt;/tt&gt; with &lt;tt class="docutils literal"&gt;c.base&lt;/tt&gt;. The value &lt;tt class="docutils literal"&gt;c.flags.owndata&lt;/tt&gt; is therefore &lt;tt class="docutils literal"&gt;False&lt;/tt&gt; whereas &lt;tt class="docutils literal"&gt;a.flags.owndata&lt;/tt&gt; is &lt;tt class="docutils literal"&gt;True&lt;/tt&gt;. The
&lt;a class="reference external" href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ndarray.base.html"&gt;base&lt;/a&gt; field is also pointing to the buffer object if the array is constructed by a buffer.&lt;/p&gt;
&lt;p&gt;The C field &lt;tt class="docutils literal"&gt;weakreflist&lt;/tt&gt; is a pointer to weak references. More information is given by the &lt;a class="reference external" href="https://docs.python.org/3/library/weakref.html"&gt;documentation of the weakref module&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="id1"&gt;
&lt;h3&gt;PyObject_HEAD&lt;/h3&gt;
&lt;p&gt;There is one last thing in the C structure we didn't cover yet: &lt;tt class="docutils literal"&gt;PyObject_HEAD&lt;/tt&gt;. &lt;a class="reference external" href="https://docs.python.org/dev/c-api/structures.html#c.PyObject_HEAD"&gt;PyObject_HEAD&lt;/a&gt; is a macro defined as (see &lt;a class="reference external" href="https://github.com/python/cpython/blob/master/Include/object.h#L82-L83"&gt;source code of PyObject_HEAD&lt;/a&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;PyObject&lt;/span&gt; &lt;span class="n"&gt;ob_base&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It is used for objects without a varying length as it is the case with an &lt;cite&gt;ndarray&lt;/cite&gt;.&lt;/p&gt;
&lt;p&gt;PyObject is defined as (see &lt;a class="reference external" href="https://github.com/python/cpython/blob/master/Include/object.h#L106-L110"&gt;source code of PyObject&lt;/a&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;_object&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;_PyObject_HEAD_EXTRA&lt;/span&gt;
    &lt;span class="n"&gt;Py_ssize_t&lt;/span&gt; &lt;span class="n"&gt;ob_refcnt&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;_typeobject&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;ob_type&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;PyObject&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The macro &lt;a class="reference external" href="https://github.com/python/cpython/blob/master/Include/object.h#L69-L80"&gt;_PyObject_HEAD_EXTRA&lt;/a&gt; is empty, except if you turn on reference tracing (&lt;tt class="docutils literal"&gt;Py_TRACE_REFS&lt;/tt&gt;).&lt;/p&gt;
&lt;p&gt;&lt;tt class="docutils literal"&gt;ob_refcnt&lt;/tt&gt; is used for reference counting: If this count hits zero then CPython will free all the resources used by the object.&lt;/p&gt;
&lt;p&gt;The &lt;tt class="docutils literal"&gt;ob_type&lt;/tt&gt; member of this structure contains a pointer to the type (see the code source of the &lt;a class="reference external" href="https://github.com/python/cpython/blob/master/Include/object.h#L343-L436"&gt;definition of PyTypeObject&lt;/a&gt;: &lt;tt class="docutils literal"&gt;PyTypeObject&lt;/tt&gt; is an alias of &lt;tt class="docutils literal"&gt;struct _typeobject&lt;/tt&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="python-implementations-without-external-library"&gt;
&lt;h2&gt;Python implementations without external library&lt;/h2&gt;
&lt;p&gt;We saw how data is stored in a Numpy ndarray. If we want to store an array in Python, we could either use the &lt;a class="reference external" href="https://docs.python.org/3/library/array.html"&gt;array module&lt;/a&gt; which stores data compactly and thus requires the type of each element to be the same, or use other containers such as lists.&lt;/p&gt;
&lt;p&gt;The drawback of Python containers is that each element is an object and thus is implemented in C as a PyObject, with the following structure:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;_object&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;_PyObject_HEAD_EXTRA&lt;/span&gt;
    &lt;span class="n"&gt;Py_ssize_t&lt;/span&gt; &lt;span class="n"&gt;ob_refcnt&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;_typeobject&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;ob_type&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;PyObject&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Each object adds fields to this structure to store its data (as it is the case for the ndarray). So more memory is used to store the pointer to the type and the reference count and also the elements are not stored contiguously so the access is slower due to cache efficiency.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="from-ndarray-to-numpy-dense-matrix"&gt;
&lt;h2&gt;From ndarray to Numpy dense matrix&lt;/h2&gt;
&lt;p&gt;Numpy dense matrix is a thin layer on top of ndarray to provide facilities for linear algebra. The &lt;a class="reference external" href="https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html"&gt;differences between dense matrices and ndarrays&lt;/a&gt; are given in the Numpy documentation. We can see their implementation in the &lt;a class="reference external" href="https://github.com/numpy/numpy/blob/v1.15.1/numpy/matrixlib/defmatrix.py#L70-L999"&gt;source code of Numpy dense matrix&lt;/a&gt;. Their use is now deprecated, since one of their main advantages was the matrix multiplication with the &lt;tt class="docutils literal"&gt;*&lt;/tt&gt; operator but &lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0465/"&gt;PEP 465&lt;/a&gt; introduced the &lt;tt class="docutils literal"&gt;@&lt;/tt&gt; operator to provide it.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="take-away"&gt;
&lt;h2&gt;Take away&lt;/h2&gt;
&lt;p&gt;Here are a few things to remember from this blog post:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;An ndarray is way more efficient to store a dense matrix than a Python list of values.&lt;/li&gt;
&lt;li&gt;We can compute the size of an ndarray &lt;em&gt;a priori&lt;/em&gt; by multiplying the number of elements by the number of bytes to store one element and a few extra bytes which are negligible.&lt;/li&gt;
&lt;li&gt;We can reduce the size of an array by selecting the number of bytes to encode each entry.&lt;/li&gt;
&lt;li&gt;Transposition is very efficient since it is just a flag to set: the whole data does not change.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;script type='text/javascript'&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="Python"></category></entry><entry><title>Data classes in Python</title><link href="https://smorbieu.gitlab.io/data-classes-in-python" rel="alternate"></link><published>2018-10-27T19:00:00+02:00</published><updated>2018-10-27T19:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2018-10-27:/data-classes-in-python</id><summary type="html">&lt;p class="first last"&gt;This blob post presents the brand-new Python data classes feature and its benefits.&lt;/p&gt;
</summary><content type="html">
&lt;p&gt;Data classes are a brand-new feature in Python 3.7 (&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0557"&gt;PEP 557&lt;/a&gt;).
They have a lot of benefits since they are a way to:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;declare a type for pieces of data, enabling IDEs autocomplete and type checking features;&lt;/li&gt;
&lt;li&gt;reduce the code size by using a concise syntax for classes definitions.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These two points are demonstrated throughout this blog post.&lt;/p&gt;
&lt;div class="section" id="data-classes-as-data-types"&gt;
&lt;h2&gt;Data classes as data types&lt;/h2&gt;
&lt;p&gt;Data can be represented by several ways:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;For atomic elements, we can use basic types such as &lt;tt class="docutils literal"&gt;int&lt;/tt&gt;, &lt;tt class="docutils literal"&gt;float&lt;/tt&gt; or &lt;tt class="docutils literal"&gt;str&lt;/tt&gt;.&lt;/li&gt;
&lt;li&gt;For more advanced pieces of data, we can use containers, such as &lt;tt class="docutils literal"&gt;list&lt;/tt&gt; or &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt;. Containers can store basic types and also be nested, allowing complex data representations.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The container types are however very generic since a &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt; does not impose restrictions on the keys it stores. We therefore often use classes to store data. It enables a usefull autocomplete feature provided by IDEs. The class name is used to represent the type of the instance of the class.&lt;/p&gt;
&lt;p&gt;Let's see a small example of a class in Python 3:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;

&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;tt class="docutils literal"&gt;bob&lt;/tt&gt; is an instance of the class &lt;tt class="docutils literal"&gt;User&lt;/tt&gt;. The same information can be represented by a &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="s1"&gt;'age'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;However, using the former is handy since it enables IDE features:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Pycharm autocomplete dropdown on a an instance of a the User class." src="https://smorbieu.gitlab.io/images/type_systems/class-autocomplete.png"/&gt;
&lt;/div&gt;
&lt;p&gt;In order to enhance the powers of the IDE, we can add type informations on the fields:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Since for storing data, we often set all the arguments of the &lt;tt class="docutils literal"&gt;__init__&lt;/tt&gt; method as fields of the object, we may prefer a more concise syntax: data classes.
Data classes are a new way to define classes in Python:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;dataclasses&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;
   &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It defines automatically the &lt;tt class="docutils literal"&gt;__init__&lt;/tt&gt; method. Data classes are regular classes, the only difference being the way to define the class.
We will see in the following section that data classes define other usefull methods automatically.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="data-classes-as-object-factories"&gt;
&lt;h2&gt;Data classes as object factories&lt;/h2&gt;
&lt;p&gt;The drawbacks when definining a class is that you need to define some methods for your objects to behave nicely:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;have a readable and usefull representation of an object,&lt;/li&gt;
&lt;li&gt;compare the equality of two objects in a natural way,&lt;/li&gt;
&lt;li&gt;use objects as keys of a dictionary.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Data classes automatically handle this for you as we will see in this section.&lt;/p&gt;
&lt;div class="section" id="have-a-readable-and-usefull-representation-of-an-object"&gt;
&lt;h3&gt;Have a readable and usefull representation of an object&lt;/h3&gt;
&lt;p&gt;Two methods are used to have a representation of an object: &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt;:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;The &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt; method is called by the built-in function &lt;tt class="docutils literal"&gt;str&lt;/tt&gt; and therefore by &lt;tt class="docutils literal"&gt;print&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;format&lt;/tt&gt;. It should give a readable representation of the object.&lt;/li&gt;
&lt;li&gt;The &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt; method is called by the buit-in function &lt;tt class="docutils literal"&gt;repr&lt;/tt&gt;. If possible it should be a valid Python expression enabling to reconstruct the object. It should be unambiguous since it is typically used for debugging.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If &lt;tt class="docutils literal"&gt;bob&lt;/tt&gt; is a &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt;, the following code:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'Bob'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'age'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;whereas if &lt;tt class="docutils literal"&gt;bob&lt;/tt&gt; is an instance of &lt;tt class="docutils literal"&gt;User&lt;/tt&gt;, it outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;__main__&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;User&lt;/span&gt; &lt;span class="nb"&gt;object&lt;/span&gt; &lt;span class="n"&gt;at&lt;/span&gt; &lt;span class="mh"&gt;0x105c56780&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In order to have a readable output we can define the method &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt; of the class &lt;tt class="docutils literal"&gt;User&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;
      &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;

   &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__str__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"User:&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;name: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;age: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;With this definition, &lt;tt class="docutils literal"&gt;print(bob)&lt;/tt&gt; now outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Bob&lt;/span&gt;
&lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It is now as informative as the &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt; version. However &lt;tt class="docutils literal"&gt;repr(bob)&lt;/tt&gt; remains unchanged. If we implement &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt; the following way:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__repr__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"User(&lt;/span&gt;&lt;span class="se"&gt;\"&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\"&lt;/span&gt;&lt;span class="s2"&gt;, &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;)"&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;we have a usefull representation of the object. The output of &lt;tt class="docutils literal"&gt;repr&lt;/tt&gt; is now a Python expression we can evaluate in order to produce the same object:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;bob_copy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;eval&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;repr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;With data classes, the &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt; methods are implemented automatically, so both &lt;tt class="docutils literal"&gt;repr(bob)&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;str(bob)&lt;/tt&gt; output: &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;"User(name='Bob',&lt;/span&gt; age=20)"&lt;/tt&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="compare-the-equality-of-two-objects-in-a-natural-way"&gt;
&lt;h3&gt;Compare the equality of two objects in a natural way&lt;/h3&gt;
&lt;p&gt;When using dictionaries, the equality behaves as expected:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'age'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="n"&gt;alice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Alice"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'age'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="n"&gt;bob_copy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'age'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;alice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;bob_copy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs : &lt;tt class="docutils literal"&gt;True False True&lt;/tt&gt;. However it seems unintuitive when using the above defined &lt;tt class="docutils literal"&gt;User&lt;/tt&gt; class:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;alice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Alice"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;bob_copy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;alice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;bob_copy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs &lt;tt class="docutils literal"&gt;True False False&lt;/tt&gt; without data classes and &lt;tt class="docutils literal"&gt;True False True&lt;/tt&gt; with data classes.
When using data classes, it behaves like the dictionary version. It is because data classes define automatically the &lt;tt class="docutils literal"&gt;__eq__&lt;/tt&gt; method.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="use-objects-as-keys-of-a-dictionary"&gt;
&lt;h3&gt;Use objects as keys of a dictionary&lt;/h3&gt;
&lt;p&gt;Say we want store a mapping between users and an other object (&lt;em&gt;e.g.&lt;/em&gt; an id in a database). We cannot use &lt;tt class="docutils literal"&gt;dict&lt;/tt&gt; nor the above &lt;tt class="docutils literal"&gt;User&lt;/tt&gt; class since it creates an error &lt;tt class="docutils literal"&gt;TypeError: unhashable type&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;We can instead use tuples or &lt;a class="reference external" href="https://docs.python.org/3/library/collections.html#collections.namedtuple"&gt;namedtuples&lt;/a&gt; but they have other drawbacks (see
&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0557/#why-not-just-use-namedtuple"&gt;Why not just use namedtuple?&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Data classes can generate automatically the &lt;tt class="docutils literal"&gt;__hash__&lt;/tt&gt; method when defined as frozen:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;dataclasses&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;frozen&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;
   &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Instances of &lt;tt class="docutils literal"&gt;User&lt;/tt&gt; can now be used as keys of a dictionary:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="data-classes-are-regular-python-classes"&gt;
&lt;h3&gt;Data classes are regular Python classes&lt;/h3&gt;
&lt;p&gt;Since data classes produce regular Python classes, we can define methods. For instance, we can define the &lt;tt class="docutils literal"&gt;get_older&lt;/tt&gt; method and the &lt;tt class="docutils literal"&gt;is_an_adult&lt;/tt&gt; &lt;a class="reference external" href="https://docs.python.org/3/library/functions.html#property"&gt;property&lt;/a&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;dataclasses&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_older&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="nd"&gt;@property&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;is_an_adult&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;18&lt;/span&gt;

&lt;span class="n"&gt;bob&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;17&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;is_an_adult&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_older&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bob&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;is_an_adult&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Data classes generate automatically the &lt;tt class="docutils literal"&gt;__init__&lt;/tt&gt; method. Other initialization code should be put in the &lt;tt class="docutils literal"&gt;__post_init__&lt;/tt&gt; method which is called just after the init as its name suggests.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="conclusion"&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Data classes are a new way to define classes in Python.&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;Since the resulting classes are regular Python classes, we can take advantage of their benefits: implement some methods and use the autocomplete features provided by IDEs for instance.&lt;/li&gt;
&lt;li&gt;Their syntax is more concise, and they generate automatically some methods such as &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt;, &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;__eq__&lt;/tt&gt;.&lt;/li&gt;
&lt;li&gt;They can easily be declared as frozen, allowing for instance to use them as keys of a dictionary (the &lt;tt class="docutils literal"&gt;__hash__&lt;/tt&gt; method is generated automatically in this case).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This new feature is particularly interesting for data science applications because we always have to define data entities and manipulate them. It makes code more readable, less tedious to write and provides static type checking eases.&lt;/p&gt;
&lt;/div&gt;
</content><category term="Python"></category></entry><entry><title>Static typing in Python</title><link href="https://smorbieu.gitlab.io/static-typing-in-python" rel="alternate"></link><published>2018-10-13T19:00:00+02:00</published><updated>2018-10-13T19:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2018-10-13:/static-typing-in-python</id><summary type="html">&lt;p class="first last"&gt;This article covers static typing in Python: how and why type annotate Python code, how to type check statically, and how to enable powerful IDEs features.&lt;/p&gt;
</summary><content type="html">
&lt;p&gt;In a &lt;a class="reference external" href="https://smorbieu.gitlab.io/key-differences-between-mainly-used-languages-for-data-science"&gt;previous blog post&lt;/a&gt;, I explained what static typing is, and presented a small example in Scala. We saw that static typing enables to spot some errors before executing the program.
This is one of the reasons why Scala and Java are used in production for data pipelines.
As Python is often used by data scientists to process data, early catching obviously (through type checking) erroneous code is beneficial for an industrialization of it, without rewriting it into another language.&lt;/p&gt;
&lt;p&gt;Luckily, Python also has optional static typing since version 3.5. It enables types checking before execution with tools such as &lt;a class="reference external" href="http://mypy-lang.org/"&gt;mypy&lt;/a&gt;, but also other powerfull features for IDEs as we will see in this blog post.&lt;/p&gt;
&lt;p&gt;&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0482/"&gt;PEP 582&lt;/a&gt; gives an overview for type hints before it was adopted by Python. The next section provides more references to type hints in Python, and presents some examples of the syntax.&lt;/p&gt;
&lt;div class="section" id="type-annotations-in-python"&gt;
&lt;h2&gt;Type annotations in Python&lt;/h2&gt;
&lt;p&gt;&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0483/"&gt;PEP 483&lt;/a&gt; introduced a discussion on type hints for Python. This PEP has the type "informational", meaning (see &lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0001/"&gt;PEP 1&lt;/a&gt;) that it does not propose a new feature that should be implemented.&lt;/p&gt;
&lt;p&gt;It is thus an introduction to &lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0484/"&gt;PEP 484&lt;/a&gt; which is in the "standards track", meaning it describes a new feature. The status is "provisional", &lt;em&gt;i.e.&lt;/em&gt; the proposal has been accepted for inclusion in the reference implementation.&lt;/p&gt;
&lt;p&gt;PEP 484 introduced both the &lt;a class="reference external" href="https://docs.python.org/3/library/typing.html"&gt;typing module&lt;/a&gt; and a syntax for type annotations for function signatures.&lt;/p&gt;
&lt;p&gt;Here is an instance of function annotation:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The typing module provides additional types, for instance the type &lt;tt class="docutils literal"&gt;List&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;typing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;append_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
   &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It enables also type aliases:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;typing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;

&lt;span class="n"&gt;Vector&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;normalize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Vector&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;Vector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="n"&gt;norm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;norm&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, we defined the &lt;tt class="docutils literal"&gt;Vector&lt;/tt&gt; type as an alias for the type &lt;tt class="docutils literal"&gt;List[float]&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;PEP 484 also introduced a syntax for variable annotations with comments:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;integers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;  &lt;span class="c1"&gt;# type: List[int]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0526/"&gt;PEP 526&lt;/a&gt; introduced another syntax for variable annotations without relying on comments to express the type of variables. For instance, PEP 526 allows the following syntax:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;integers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;For now, we only saw the basics of type annotations and their benefits from a documentation perspective: the documentation of the types of the inputs and outputs of functions, and the types of variables, is included into the code itself through type annotations.
It is time to see them in action for static type checking and other features.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="type-checking-with-mypy"&gt;
&lt;h2&gt;Type checking with mypy&lt;/h2&gt;
&lt;p&gt;&lt;a class="reference external" href="http://mypy-lang.org/"&gt;mypy&lt;/a&gt; is a static type checker for Python. Let's see a small example (&lt;cite&gt;example1.py&lt;/cite&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;typing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Dict&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;create_row&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'x'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
           &lt;span class="s1"&gt;'y'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
           &lt;span class="s1"&gt;'z'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;argmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;create_row&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;argmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"key: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;, value: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We created a row implemented by a dictionary where the keys are the column labels. We then print the maximum value of the row and its corresponding column.&lt;/p&gt;
&lt;p&gt;We can check the types with mypy:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;mypy example1.py
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs nothing, meaning that nothing went wrong with the type checking.&lt;/p&gt;
&lt;p&gt;Say we want to modify the implementation of a row by representing it as a list since every row values correspond to the same columns, but we forget to change the implementation of &lt;tt class="docutils literal"&gt;argmax&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;typing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Dict&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;create_row&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
    &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;argmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;create_row&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;argmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"key: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;, value: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If we run mypy on this example (&lt;cite&gt;example2.py&lt;/cite&gt;), it outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;example2.py:14: error: Argument &lt;span class="m"&gt;1&lt;/span&gt; to &lt;span class="s2"&gt;"argmax"&lt;/span&gt; has incompatible &lt;span class="nb"&gt;type&lt;/span&gt; &lt;span class="s2"&gt;"List[int]"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; expected &lt;span class="s2"&gt;"Dict[str, int]"&lt;/span&gt;
example2.py:15: error: No overload variant of &lt;span class="s2"&gt;"__getitem__"&lt;/span&gt; of &lt;span class="s2"&gt;"list"&lt;/span&gt; matches argument &lt;span class="nb"&gt;type&lt;/span&gt; &lt;span class="s2"&gt;"str"&lt;/span&gt;
example2.py:15: note: Possible overload variants:
example2.py:15: note:     def __getitem__&lt;span class="o"&gt;(&lt;/span&gt;self, int&lt;span class="o"&gt;)&lt;/span&gt; -&amp;gt; int
example2.py:15: note:     def __getitem__&lt;span class="o"&gt;(&lt;/span&gt;self, slice&lt;span class="o"&gt;)&lt;/span&gt; -&amp;gt; List&lt;span class="o"&gt;[&lt;/span&gt;int&lt;span class="o"&gt;]&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It warns about mistakes, without running the code: for instance, the annotation for the &lt;tt class="docutils literal"&gt;argmax&lt;/tt&gt; function is incompatible with the type of the &lt;tt class="docutils literal"&gt;row&lt;/tt&gt; variable given as argument.&lt;/p&gt;
&lt;p&gt;If you change the function signature by (or define a type &lt;tt class="docutils literal"&gt;Row&lt;/tt&gt; as seen previously with the type &lt;tt class="docutils literal"&gt;Vector&lt;/tt&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;argmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;and run mypy again, it outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;example2.py:10: error: &lt;span class="s2"&gt;"List[int]"&lt;/span&gt; has no attribute &lt;span class="s2"&gt;"get"&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If you run the above code, with the modification or without it, it fails and outputs the same error:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;Traceback &lt;span class="o"&gt;(&lt;/span&gt;most recent call last&lt;span class="o"&gt;)&lt;/span&gt;:
  File &lt;span class="s2"&gt;"example2.py"&lt;/span&gt;, line &lt;span class="m"&gt;14&lt;/span&gt;, in &amp;lt;module&amp;gt;
    &lt;span class="nv"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; argmax&lt;span class="o"&gt;(&lt;/span&gt;row&lt;span class="o"&gt;)&lt;/span&gt;
  File &lt;span class="s2"&gt;"example2.py"&lt;/span&gt;, line &lt;span class="m"&gt;10&lt;/span&gt;, in argmax
    &lt;span class="k"&gt;return&lt;/span&gt; max&lt;span class="o"&gt;(&lt;/span&gt;row, &lt;span class="nv"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;row.get&lt;span class="o"&gt;)&lt;/span&gt;
AttributeError: &lt;span class="s1"&gt;'list'&lt;/span&gt; object has no attribute &lt;span class="s1"&gt;'get'&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs the same error because Python does not check the type annotations.&lt;/p&gt;
&lt;p&gt;We saw how to use mypy to static check the code, but type annotations enable more powerfull features for IDEs.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="enable-the-powers-of-an-ide"&gt;
&lt;h2&gt;Enable the powers of an IDE&lt;/h2&gt;
&lt;p&gt;If you use a good Python editor such as
&lt;a class="reference external" href="https://www.jetbrains.com/pycharm/"&gt;PyCharm&lt;/a&gt;,
it can help you with the autocomplete feature by filtering and proposing only the methods available for the type.&lt;/p&gt;
&lt;p&gt;Let's see a sample code without type annotations:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Pycharm autocomplete dropdown on a code without type annotation nor defined variable passed as argument." src="https://smorbieu.gitlab.io/images/type_systems/pycharm1.png"/&gt;
&lt;/div&gt;
&lt;p&gt;Since Pycham has no information about the type of the &lt;tt class="docutils literal"&gt;row&lt;/tt&gt; argument in the &lt;tt class="docutils literal"&gt;argmax&lt;/tt&gt; function, the autocomple dropdown menu cannot propose valuable autocompletion.&lt;/p&gt;
&lt;p&gt;If however we specify the type of the argument as a list of &lt;cite&gt;int&lt;/cite&gt;, Pycharm can filter the elements of the dropdown menu, and propose only methods applicable to a list:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Pycharm autocomplete dropdown on a code with type annotation (`List[int]`) but without a defined variable passed as argument." src="https://smorbieu.gitlab.io/images/type_systems/pycharm3.png"/&gt;
&lt;/div&gt;
&lt;p&gt;If we change the type, it changes the proposed completions accordingly:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Pycharm autocomplete dropdown on a code with type annotation (`Dict[int, int]`) but without a defined variable passed as argument." src="https://smorbieu.gitlab.io/images/type_systems/pycharm4.png"/&gt;
&lt;/div&gt;
&lt;p&gt;In fact, if we don't type annotate the function, in some cases, Pycharm is smart enough to show a valuable autocomplete. This is the case if the variable is created with &lt;tt class="docutils literal"&gt;create_row&lt;/tt&gt; and passed to &lt;tt class="docutils literal"&gt;argmax&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="figure"&gt;
&lt;img alt="Pycharm autocomplete dropdown on a code without type annotation but with a defined variable passed as argument." src="https://smorbieu.gitlab.io/images/type_systems/pycharm2.png"/&gt;
&lt;/div&gt;
&lt;p&gt;Type annotations often help the IDE when it cannot infer the type.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="conclusion-and-perspectives"&gt;
&lt;h2&gt;Conclusion and perspectives&lt;/h2&gt;
&lt;p&gt;We saw how to use type annotations in Python, by:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;adding them into Python code which makes a self contained documentation,&lt;/li&gt;
&lt;li&gt;checking statically the types,&lt;/li&gt;
&lt;li&gt;and leveraging the autocomplete feature of IDEs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Type annotations are also used by data classes (&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0557/"&gt;PEP 557&lt;/a&gt;) as we will see in another blog post.&lt;/p&gt;
&lt;p&gt;We saw what is called a nominative typed system, &lt;em&gt;i.e.&lt;/em&gt; comparisons are based on the names of the types or explicit declarations. There exists a proposition (&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0544/"&gt;PEP 544&lt;/a&gt;) for a structural type system, &lt;em&gt;i.e.&lt;/em&gt; based on properties: types are considered compatible if they share the same features. It allows to avoid the inheritance of some generic classes or the support of some protocols (iterator for instance), instead the classes can be implicitly considered as a subtype of another class. It can thus be considered as static duck typing.
&lt;a class="reference external" href="https://mypy.readthedocs.io/en/latest/protocols.html"&gt;Mypy documentation on structural subtyping&lt;/a&gt; provides additional explainations.&lt;/p&gt;
&lt;/div&gt;
</content><category term="Python"></category></entry><entry><title>Encoding in Python</title><link href="https://smorbieu.gitlab.io/encoding-in-python" rel="alternate"></link><published>2018-09-29T12:00:00+02:00</published><updated>2018-09-29T12:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2018-09-29:/encoding-in-python</id><summary type="html">&lt;p class="first last"&gt;The transition from Python 2 to Python 3 caused some problems since the two versions handle text differently. First, we will see how the text is represented in Python 2 and Python 3, then how to do the conversion between the different representations, and then the different places where encoding step in: the encoding of the source code, the implicit conversions, the encoding of the inputs and outputs, and the file system encoding.&lt;/p&gt;
</summary><content type="html">
&lt;p&gt;Encoding in Python is known to cause some problems because people often overlook some essential things: whenever you have to read an input (&lt;em&gt;resp.&lt;/em&gt; write into an output), you should transform the content from (&lt;em&gt;resp.&lt;/em&gt; to) the internal representation of the language to (&lt;em&gt;resp.&lt;/em&gt; from) a sequence of bytes.&lt;/p&gt;
&lt;p&gt;For this transformation, you have to choose an encoding which specifies how the content is represented as a sequence of bytes.&lt;/p&gt;
&lt;p&gt;The transition from Python 2 to Python 3 caused some problems since the two versions handle text differently. First, we will see how the text is represented in Python 2 and Python 3, then how to do the conversion between the different representations, and then the different places where encoding step in:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;the encoding of the source code,&lt;/li&gt;
&lt;li&gt;the implicit conversions,&lt;/li&gt;
&lt;li&gt;the encoding of the input and the output,&lt;/li&gt;
&lt;li&gt;and the file system encoding.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="section" id="types-to-represent-text"&gt;
&lt;h2&gt;Types to represent text&lt;/h2&gt;
&lt;p&gt;Text in Python can be represented in several ways, especially as:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;a sequence of bytes&lt;/li&gt;
&lt;li&gt;a sequence of symbols (&lt;em&gt;i.e.&lt;/em&gt; characters)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Python 2 and 3 use different types that are summarized in this table:&lt;/p&gt;
&lt;table class="docutils"&gt;

&lt;thead&gt;
&lt;tr&gt;&lt;th class="head"&gt;Python 2&lt;/th&gt;
&lt;th class="head"&gt;Python 3&lt;/th&gt;
&lt;th class="head"&gt;Elements&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;str (ex: &lt;tt class="docutils literal"&gt;"my string"&lt;/tt&gt;)&lt;/td&gt;
&lt;td&gt;bytes (ex: &lt;tt class="docutils literal"&gt;b"my string"&lt;/tt&gt;)&lt;/td&gt;
&lt;td&gt;byte&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;unicode (ex: &lt;tt class="docutils literal"&gt;u"my string"&lt;/tt&gt;)&lt;/td&gt;
&lt;td&gt;str (ex: &lt;tt class="docutils literal"&gt;"my string"&lt;/tt&gt;)&lt;/td&gt;
&lt;td&gt;symbol&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Here, I simplified since Python offers some mutable and immutable types, for instance Python 3 uses the &lt;cite&gt;bytes&lt;/cite&gt; class for immutable sequences of single bytes, and &lt;cite&gt;bytearray&lt;/cite&gt; class for its mutable counterpart.&lt;/p&gt;
&lt;p&gt;The main point is: you can either handle text as a sequence of bytes, or as a sequence of symbols. The conversion between these two types are discussed in the following session.&lt;/p&gt;
&lt;p&gt;For &lt;tt class="docutils literal"&gt;"my string"&lt;/tt&gt; to be unicode in Python 2 (act like &lt;cite&gt;str&lt;/cite&gt; in Python 3) you can use:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;__future__&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;unicode_literals&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="transformations-between-text-representations"&gt;
&lt;h2&gt;Transformations between text representations&lt;/h2&gt;
&lt;p&gt;Let's consider a small example in Python 3:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"chaîne"&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"type of s: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"type of b: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"len(s): &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"len(b): &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"s: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"b: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We store the string &lt;tt class="docutils literal"&gt;chaîne&lt;/tt&gt; in a variable &lt;tt class="docutils literal"&gt;s&lt;/tt&gt; and store its encoding in utf-8 in the variable &lt;tt class="docutils literal"&gt;b&lt;/tt&gt;. We then print the types of the two variables, their lengths and their representations.
It outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;type&lt;/span&gt; of s: &amp;lt;class &lt;span class="s1"&gt;'str'&lt;/span&gt;&amp;gt;
&lt;span class="nb"&gt;type&lt;/span&gt; of b: &amp;lt;class &lt;span class="s1"&gt;'bytes'&lt;/span&gt;&amp;gt;
len&lt;span class="o"&gt;(&lt;/span&gt;s&lt;span class="o"&gt;)&lt;/span&gt;: &lt;span class="m"&gt;6&lt;/span&gt;
len&lt;span class="o"&gt;(&lt;/span&gt;b&lt;span class="o"&gt;)&lt;/span&gt;: &lt;span class="m"&gt;7&lt;/span&gt;
s: chaîne
b: b&lt;span class="s1"&gt;'cha\xc3\xaene'&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;First we can see that the string (&lt;em&gt;i.e.&lt;/em&gt; a sequence of symbols) &lt;tt class="docutils literal"&gt;s&lt;/tt&gt; is of length &lt;cite&gt;6&lt;/cite&gt; which seems intuitive, but &lt;tt class="docutils literal"&gt;b&lt;/tt&gt; of type &lt;cite&gt;bytes&lt;/cite&gt; (&lt;em&gt;i.e.&lt;/em&gt; a sequence of bytes) is of lenght &lt;cite&gt;7&lt;/cite&gt; which seems unintuitive. When we see their representations, we can understand better what happens: the symbol &lt;tt class="docutils literal"&gt;î&lt;/tt&gt; is transformed into two bytes (represented by &lt;tt class="docutils literal"&gt;\xc3&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;\xae&lt;/tt&gt;).&lt;/p&gt;
&lt;p&gt;Note that when printing the representations of &lt;tt class="docutils literal"&gt;s&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;b&lt;/tt&gt;, the method &lt;tt class="docutils literal"&gt;__repr__&lt;/tt&gt; of the classes &lt;cite&gt;str&lt;/cite&gt; and &lt;cite&gt;bytes&lt;/cite&gt; is applied to transform the sequence of symbols and the sequence of bytes respectively. For &lt;tt class="docutils literal"&gt;b&lt;/tt&gt;, this method transforms the sequence of bytes into a string.
The following code illustrates how the content is stored in &lt;tt class="docutils literal"&gt;b&lt;/tt&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&amp;lt;class &lt;span class="s1"&gt;'int'&lt;/span&gt;&amp;gt;
&lt;span class="m"&gt;99&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It is the wrapper, here the &lt;cite&gt;bytes&lt;/cite&gt; class, which knows how it is appropriate to represent itself since the individual elements are bytes stored as &lt;cite&gt;int&lt;/cite&gt; by Python.&lt;/p&gt;
&lt;p&gt;If you try to transform the string &lt;tt class="docutils literal"&gt;s&lt;/tt&gt; into bytes encoded with ASCII:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'ascii'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;you get an exception since you cannot represent &lt;tt class="docutils literal"&gt;î&lt;/tt&gt; with ASCII:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;UnicodeEncodeError: &lt;span class="s1"&gt;'ascii'&lt;/span&gt; codec can&lt;span class="s1"&gt;'t encode character '&lt;/span&gt;&lt;span class="se"&gt;\x&lt;/span&gt;ee&lt;span class="err"&gt;'&lt;/span&gt; in position &lt;span class="m"&gt;3&lt;/span&gt;: ordinal not in range&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="m"&gt;128&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We saw how to encode a string into bytes. We can also transform bytes to a string:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'utf-8'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;You have to be careful when selecting the encoding:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;When encoding, the encoding should support all the symbols of the string.&lt;/li&gt;
&lt;li&gt;When decoding, the encoding should correspond to the one you used for encoding it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The code:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'latin-1'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;produces the string &lt;tt class="docutils literal"&gt;"chaÃ®ne"&lt;/tt&gt;, showing how important the second point is.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="source-code-encoding"&gt;
&lt;h2&gt;Source code encoding&lt;/h2&gt;
&lt;p&gt;We previously saw that some symbols cannot be used with some encodings (ASCII cannot represent the symbol &lt;cite&gt;î&lt;/cite&gt; for instance).
If you want to use some symbols in your Python source code, you should then use an encoding that supports it.&lt;/p&gt;
&lt;p&gt;By default, the encoding of the source code is:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;utf-8 for Python 3 (&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-3120/"&gt;PEP 3120&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;ASCII for Python 2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To have the same behavior as Python 3 with Python 2, you can use at the beginning of the file (&lt;a class="reference external" href="https://www.python.org/dev/peps/pep-0263/"&gt;PEP 263&lt;/a&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# -*- coding: utf-8 -*-&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;You should also of course check that you editor is using the correct encoding.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="implicit-conversions"&gt;
&lt;h2&gt;Implicit conversions&lt;/h2&gt;
&lt;p&gt;Sometimes, Python uses implicit conversions. This is the case for instance if you try (in Python 3):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;b&lt;/span&gt;&lt;span class="s2"&gt;"my bytes"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The bytes &lt;tt class="docutils literal"&gt;b"my bytes"&lt;/tt&gt; is converted implicitly into a string. This is also the case with the built-in &lt;tt class="docutils literal"&gt;print&lt;/tt&gt; or &lt;tt class="docutils literal"&gt;str&lt;/tt&gt; functions. They apply the &lt;tt class="docutils literal"&gt;__str__&lt;/tt&gt; method of the class of the object to convert it into a string.&lt;/p&gt;
&lt;p&gt;By default, the encoding used for implicit conversions is:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;utf-8 for Python 3&lt;/li&gt;
&lt;li&gt;ASCII for Python 2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can check it with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getdefaultencoding&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="input-and-output-encoding"&gt;
&lt;h2&gt;Input and output encoding&lt;/h2&gt;
&lt;p&gt;Python can read from the input stream &lt;tt class="docutils literal"&gt;sys.stdin&lt;/tt&gt;, for instance with the &lt;tt class="docutils literal"&gt;input&lt;/tt&gt; function. It can write to the standard output &lt;tt class="docutils literal"&gt;sys.stdout&lt;/tt&gt; with the &lt;tt class="docutils literal"&gt;print&lt;/tt&gt; function and also to the standard error &lt;tt class="docutils literal"&gt;sys.stderr&lt;/tt&gt; for its error messages. You can check their encodings with (&lt;cite&gt;ioencodings.py&lt;/cite&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdin: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdin&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdout: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stderr: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;You can define the encoding with the &lt;tt class="docutils literal"&gt;PYTHONIOENCODING&lt;/tt&gt; environment variable.&lt;/p&gt;
&lt;p&gt;Python behaves differently if you are in a shell or if you uses pipes:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;python ioencoding.py
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs (it can differ depending on your environment) both in Python 2 and 3:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;stdin: UTF-8
stdout: UTF-8
stderr: UTF-8
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;However:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;python ioencoding.py &lt;span class="p"&gt;|&lt;/span&gt; cat
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs the same thing with Python 3 but with Python 2 it outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;stdin: UTF-8
stdout: None
stderr: UTF-8
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here is a broader example (&lt;cite&gt;encodingtest.py&lt;/cite&gt;) you can experiment with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="c1"&gt;# -*- coding: utf-8 -*-&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;__future__&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;unicode_literals&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nn"&gt;locale&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nn"&gt;os&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"IO encodings:"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdin: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdin&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdout: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stderr: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;default encoding: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getdefaultencoding&lt;/span&gt;&lt;span class="p"&gt;()))&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;tty(-like) device?"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdin: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdin&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;isatty&lt;/span&gt;&lt;span class="p"&gt;()))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stdout: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;isatty&lt;/span&gt;&lt;span class="p"&gt;()))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"stderr: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;isatty&lt;/span&gt;&lt;span class="p"&gt;()))&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;PYTHONIOENCODING: &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"PYTHONIOENCODING"&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"î"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;chr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;238&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ā"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;chr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;For instance with Python 3:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt; python encodingtest.py
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;IO encodings:
stdin: UTF-8
stdout: UTF-8
stderr: UTF-8

default encoding: utf-8

tty&lt;span class="o"&gt;(&lt;/span&gt;-like&lt;span class="o"&gt;)&lt;/span&gt; device?
stdin: False
stdout: True
stderr: True

PYTHONIOENCODING: None
î
î
Ā
Ā
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;and with Python 2:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;IO encodings:
stdin: None
stdout: UTF-8
stderr: UTF-8

default encoding: ascii

tty&lt;span class="o"&gt;(&lt;/span&gt;-like&lt;span class="o"&gt;)&lt;/span&gt; device?
stdin: False
stdout: True
stderr: True

PYTHONIOENCODING: None
î
�
Ā
Traceback &lt;span class="o"&gt;(&lt;/span&gt;most recent call last&lt;span class="o"&gt;)&lt;/span&gt;:
  File &lt;span class="s2"&gt;"encodingtest.py"&lt;/span&gt;, line &lt;span class="m"&gt;24&lt;/span&gt;, in &amp;lt;module&amp;gt;
    print&lt;span class="o"&gt;(&lt;/span&gt;chr&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="m"&gt;256&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
ValueError: chr&lt;span class="o"&gt;()&lt;/span&gt; arg not in range&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="m"&gt;256&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It produces an an error since in Python 2 &lt;tt class="docutils literal"&gt;chr&lt;/tt&gt; creates a Python 2 &lt;cite&gt;str&lt;/cite&gt; for values in between 0 and 255 (a byte is &lt;span class="math"&gt;\(2^8 = 256\)&lt;/span&gt; bits and Python 2 &lt;cite&gt;str&lt;/cite&gt; are sequences of bytes).
For 0 to 127, it corresponds to its ASCII code.
In Python 3, &lt;tt class="docutils literal"&gt;chr&lt;/tt&gt; created a Python 3 &lt;cite&gt;str&lt;/cite&gt; for values corresponding to its Unicode code (hence a broader range).&lt;/p&gt;
&lt;p&gt;Note also that it produces &lt;tt class="docutils literal"&gt;�&lt;/tt&gt; instead of &lt;tt class="docutils literal"&gt;î&lt;/tt&gt; because the extended ASCII code 238 corresponds to it (238 is the Unicode code for &lt;tt class="docutils literal"&gt;î&lt;/tt&gt;, hence it worked as intended in Python 3).&lt;/p&gt;
&lt;p&gt;If we specify the encoding for the input and outputs to be ASCII (it was previously undefined for the input with Python 2 because of the pipe):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="nv"&gt;PYTHONIOENCODING&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;ascii python2 encodingtest.py
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;it outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;IO encodings:
stdin: ascii
stdout: ascii
stderr: ascii

default encoding: ascii

tty&lt;span class="o"&gt;(&lt;/span&gt;-like&lt;span class="o"&gt;)&lt;/span&gt; device?
stdin: False
stdout: True
stderr: True

PYTHONIOENCODING: ascii
Traceback &lt;span class="o"&gt;(&lt;/span&gt;most recent call last&lt;span class="o"&gt;)&lt;/span&gt;:
  File &lt;span class="s2"&gt;"encodingtest.py"&lt;/span&gt;, line &lt;span class="m"&gt;20&lt;/span&gt;, in &amp;lt;module&amp;gt;
    print&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"î"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
UnicodeEncodeError: &lt;span class="s1"&gt;'ascii'&lt;/span&gt; codec can&lt;span class="s1"&gt;'t encode character u'&lt;/span&gt;&lt;span class="se"&gt;\x&lt;/span&gt;ee&lt;span class="err"&gt;'&lt;/span&gt; in position &lt;span class="m"&gt;0&lt;/span&gt;: ordinal not in range&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="m"&gt;128&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we have an error since the &lt;tt class="docutils literal"&gt;print&lt;/tt&gt; function encodes the &lt;cite&gt;unicode&lt;/cite&gt; string (because of &lt;tt class="docutils literal"&gt;unicode_literals&lt;/tt&gt; with Python 2) to a sequence of bytes in ASCII (the encoding for &lt;tt class="docutils literal"&gt;sys.sdtout&lt;/tt&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="file-system-encoding"&gt;
&lt;h2&gt;File system encoding&lt;/h2&gt;
&lt;p&gt;The last encoding setting to be distinguished is the encoding used for the file system. It is used to convert between Unicode filenames and bytes filenames.
You can check it with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getfilesystemencoding&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="summary"&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;In this blog post, we saw that Python has two main types to handle the texts:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;a sequence of symbols, allowing to handle texts in an intuitive way;&lt;/li&gt;
&lt;li&gt;a sequence of bytes, used when you have to transfer text between Python and other software (especially the file system).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We also saw that Python 2 and 3 behave differently, Python 3 fixing some bad choices of Python 2.&lt;/p&gt;
&lt;p&gt;Encoding appears at different places, when:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;writing the source code itself,&lt;/li&gt;
&lt;li&gt;implicitly converting the two main types,&lt;/li&gt;
&lt;li&gt;reading and writing to the inputs and outputs,&lt;/li&gt;
&lt;li&gt;and handling the filenames.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I hope this post clarifies some misconceptions about Python encoding.&lt;/p&gt;
&lt;/div&gt;
&lt;script type='text/javascript'&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</content><category term="Python"></category></entry><entry><title>Key differences between mainly used languages for data science</title><link href="https://smorbieu.gitlab.io/key-differences-between-mainly-used-languages-for-data-science" rel="alternate"></link><published>2018-09-01T19:00:00+02:00</published><updated>2018-09-01T19:00:00+02:00</updated><author><name>Stanislas Morbieu</name></author><id>tag:smorbieu.gitlab.io,2018-09-01:/key-differences-between-mainly-used-languages-for-data-science</id><summary type="html">&lt;p class="first last"&gt;This blog post introduces the notions of strongly and weakly typed in one hand, and the notion of static and dynamic typing in the other hand. It is illustrated with four languages commonly used in data science pipelines.&lt;/p&gt;
</summary><content type="html">
&lt;p&gt;Two notions of typing for programming languages are to be distinguished:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;strong vs weak&lt;/li&gt;
&lt;li&gt;static vs dynamic&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this blog post, the two notions will first be explained and then illustrated with four programming languages widely used in data science pipelines: Python, Scala, Javascript and C.&lt;/p&gt;
&lt;div class="section" id="strongly-vs-weakly-typed"&gt;
&lt;h2&gt;Strongly vs weakly typed&lt;/h2&gt;
&lt;p&gt;Defining what is a strongly typed, or a weakly typed language, is &lt;a class="reference external" href="https://en.wikipedia.org/wiki/Strong_and_weak_typing"&gt;controversial&lt;/a&gt;. Here, I consider weakly typed languages as languages that may perform implicit type conversion at runtime, thus producing sometimes unpredictable results. At the extreme, Assembly language for instance is said to be &lt;em&gt;untyped&lt;/em&gt; since there is no type checking. The absence of type checking allows a lot of freedom, necessary for strong optimizations (except for very specific projects, you don't write Assembly code, you write in a higher level language and the compiler produces Assembly code for you).&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="static-vs-dynamic-typing"&gt;
&lt;h2&gt;Static vs dynamic typing&lt;/h2&gt;
&lt;p&gt;If the type of a variable is known at compile time, the language is called statically typed. It allows to catch trivial bugs at compile time, &lt;em&gt;i.e.&lt;/em&gt; before execution.&lt;/p&gt;
&lt;p&gt;Static typing does not imply that the programmer has to specify the type of each variable: some languages offer &lt;em&gt;type inference&lt;/em&gt;. It is the case for example of Scala and OCaml.&lt;/p&gt;
&lt;p&gt;For dynamically typed languages, the type is associated with the value at run-time.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="examples"&gt;
&lt;h2&gt;Examples&lt;/h2&gt;
&lt;p&gt;To get a better understanding of the weaknesses of some languages, we are going to see the four different cases:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;weakly and dynamically typed&lt;/li&gt;
&lt;li&gt;strongly and dynamically typed&lt;/li&gt;
&lt;li&gt;strongly and statically typed&lt;/li&gt;
&lt;li&gt;weakly and statically typed&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="section" id="javascript-weakly-and-dynamically-typed"&gt;
&lt;h3&gt;Javascript: weakly and dynamically typed&lt;/h3&gt;
&lt;p&gt;Let's define a small script, &lt;cite&gt;add_numbers.js&lt;/cite&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;
&lt;span class="nx"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;5&lt;/span&gt;

&lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We defined a function &lt;tt class="docutils literal"&gt;add_numbers&lt;/tt&gt; which takes two arguments &lt;tt class="docutils literal"&gt;a&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;b&lt;/tt&gt; and return their sum. We apply it with a string &lt;tt class="docutils literal"&gt;c&lt;/tt&gt;, and an int &lt;tt class="docutils literal"&gt;n&lt;/tt&gt;, and write the result to the standard output. We can run the above script with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;node add_numbers.js
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs &lt;tt class="docutils literal"&gt;55&lt;/tt&gt;. Javascript converted silently the integer &lt;tt class="docutils literal"&gt;n&lt;/tt&gt; to a string, and concatenated the two strings. If you expect to see &lt;tt class="docutils literal"&gt;10&lt;/tt&gt;, inverting the two arguments does not help you, since it produces the same result: "&lt;tt class="docutils literal"&gt;+&lt;/tt&gt;" concatenates strings as soon as one of its operands is a string.
This pitfall can be avoided by &lt;a class="reference external" href="https://smorbieu.gitlab.io/drafts/from-javascript-to-typescript.html"&gt;checking the types automatically beforehand&lt;/a&gt; (&lt;em&gt;e.g.&lt;/em&gt; with Typescript), as we will see in another blog post.
It also makes me prefer strongly typed languages, as we will see with Python.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="python-strongly-and-dynamically-typed"&gt;
&lt;h3&gt;Python: strongly and dynamically typed&lt;/h3&gt;
&lt;p&gt;Let's write the same script, but this time in Python (&lt;cite&gt;add_numbers.py&lt;/cite&gt;):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

&lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;
&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;

&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The function &lt;tt class="docutils literal"&gt;add_numbers&lt;/tt&gt; takes two arguments &lt;tt class="docutils literal"&gt;a&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;b&lt;/tt&gt;, and return their sum. We apply it, as previously in Javascript, with a string &lt;tt class="docutils literal"&gt;c&lt;/tt&gt; and an int &lt;tt class="docutils literal"&gt;n&lt;/tt&gt;. When running the above script:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;python3 add_numbers.py
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;TypeError: can only concatenate str &lt;span class="o"&gt;(&lt;/span&gt;not &lt;span class="s2"&gt;"int"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; to str
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This example shows that Python is strongly typed since it doesn't allow to sum an int and a string. It prevents erroneous results by raising an &lt;a class="reference external" href="https://docs.python.org/3.7/tutorial/errors.html"&gt;exception&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This error is however produced at run-time because Python is dynamically typed. It is not ideal since the error only pops up when the code snippet is executed. It means that if you have a long running piece of code before your mistake (forgetting to convert the string to an int for instance), you have to wait that amount of time to notice it, which slows down your development process.&lt;/p&gt;
&lt;p&gt;In another blog post, we will see how to use &lt;a class="reference external" href="https://smorbieu.gitlab.io/static-typing-in-python"&gt;static typing in Python&lt;/a&gt;, but for now, let's see another language which is statically typed: Scala.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="scala-strongly-and-statically-typed"&gt;
&lt;h3&gt;Scala: strongly and statically typed&lt;/h3&gt;
&lt;p&gt;Here we define the same function in Scala, this time specifying the type of the arguments, and apply it with a string and an integer:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt;
&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;

&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;result&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We can run this script (&lt;cite&gt;add_numbers.scala&lt;/cite&gt;) with the Scala REPL. It compiles it and executes the resulting program:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;scala add_numbers.scala
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;add_numbers.scala:9: error: &lt;span class="nb"&gt;type&lt;/span&gt; mismatch&lt;span class="p"&gt;;&lt;/span&gt;
 found   : String
 required: Int
   val &lt;span class="nv"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; add_numbers&lt;span class="o"&gt;(&lt;/span&gt;c, n&lt;span class="o"&gt;)&lt;/span&gt;
                            ^
one error found
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The error is found at compile time. To convince you, we can separate the two steps: compile and run. For this, we have to wrap the script into an object to produce a standalone Scala code:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="k"&gt;object&lt;/span&gt; &lt;span class="nc"&gt;AddNumbers&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Array&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;])&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Unit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt;
    &lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;

    &lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
  &lt;span class="o"&gt;}&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="k"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="k"&gt;:&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt;
  &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Wrapping the script into an object was automatically done by the Scala REPL, which is a tool to evaluate expressions in Scala.&lt;/p&gt;
&lt;p&gt;Here, we also show how to use type inference in Scala: the types of &lt;tt class="docutils literal"&gt;c&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;n&lt;/tt&gt; are inferred to be &lt;tt class="docutils literal"&gt;String&lt;/tt&gt; and &lt;tt class="docutils literal"&gt;Int&lt;/tt&gt; respectively. The function &lt;tt class="docutils literal"&gt;add_numbers&lt;/tt&gt; takes two arguments of type &lt;tt class="docutils literal"&gt;Int&lt;/tt&gt; and return a value of the same type.&lt;/p&gt;
&lt;p&gt;We can compile the Scala code with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;scalac add_numbers.scala
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which outputs:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;add_numbers.scala:6: error: &lt;span class="nb"&gt;type&lt;/span&gt; mismatch&lt;span class="p"&gt;;&lt;/span&gt;
 found   : String
 required: Int
    val &lt;span class="nv"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; c + n
                 ^
one error found
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Being able to detect such mistakes at compile time is extremely powerfull. This is possible with languages that are both strongly and statically typed. If the language is weakly typed, we fall into one of the pitfalls of Javascript: wrong results at run-time, as we will see with C.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="c-weakly-and-statically-typed"&gt;
&lt;h3&gt;C: weakly and statically typed&lt;/h3&gt;
&lt;p&gt;Here is again the same example, written in C:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;stdio.h&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;add_numbers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;printf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"%d&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It can be compiled with:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;gcc -w add_numbers.c
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Which produces the executable &lt;cite&gt;add_numbers.out&lt;/cite&gt;.&lt;/p&gt;
&lt;p&gt;When running the executable:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;./add_numbers.out
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;It outputs &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-73&lt;/span&gt;&lt;/tt&gt;. This example shows the danger when using weakly typed languages.&lt;/p&gt;
&lt;p&gt;In fact, when running the compiler, I disabled the warnings with the &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-w&lt;/span&gt;&lt;/tt&gt; option. A good compiler with all the warnings activated can detect such things, for instance when compiling without the &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-w&lt;/span&gt;&lt;/tt&gt; flag:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;add_numbers.c:9:10: warning: incompatible pointer to integer conversion initializing &lt;span class="s1"&gt;'char'&lt;/span&gt; with an expression
      of &lt;span class="nb"&gt;type&lt;/span&gt; &lt;span class="s1"&gt;'char [2]'&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;-Wint-conversion&lt;span class="o"&gt;]&lt;/span&gt;
    char &lt;span class="nv"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         ^   ~~~
&lt;span class="m"&gt;1&lt;/span&gt; warning generated.
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In more complicated cases (for instance using &lt;cite&gt;void pointers&lt;/cite&gt;), the compiler does not catch the errors.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section" id="conclusion"&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;We have seen in this blog post two notions of how the computer languages handle the types: the notion of static and dynamic typing, and the notion of strong and weak typing.&lt;/p&gt;
&lt;p&gt;Each case have been illustrated with one programming language:&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;Scala is both strongly and statically typed: It is usefull to catch the potential erroneous code at an early stage. Scala is therefore often used in data engineering pipelines, where you want to spot as much errors as you can, before going into production.&lt;/li&gt;
&lt;li&gt;Python is strongly and dynamically typed: Its strong type system allows to catch erroneous code, but its dynamic nature makes you spot them only at run-time. Python is often used by data scientists, and its dynamic nature is justified since you want to see the results immediately, avoiding an often slow compilation. The REPL allows to run code as you write it (and it is faster than with some statically typed languages which provide also a REPL, such as Scala).&lt;/li&gt;
&lt;li&gt;C is statically but weakly typed: The weakly type system allows some freedom for speed improvements and allows to handle the memory at a low level. It is thus perfectly fine to use it when you know what you are doing, for tasks where the memory footprint and speed are important.&lt;/li&gt;
&lt;li&gt;Javascript is dynamically and weakly typed: It is sometimes convenient since, when you know how it works, the interpreter does the job for you, as it handles automatically the conversions.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><category term="Javascript"></category><category term="Python"></category><category term="Scala"></category><category term="C"></category></entry></feed>