<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Wasim Thabraze</title>
    <description>Hi, I'm Wasim. Here, I mainly write about Golang, Open source and random ruminations on programming and infrastructure.
</description>
    <link>http://www.thabraze.me/</link>
    <atom:link href="http://www.thabraze.me/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 14 Jun 2019 03:57:45 +0000</pubDate>
    <lastBuildDate>Fri, 14 Jun 2019 03:57:45 +0000</lastBuildDate>
    <generator>Jekyll v3.8.5</generator>
    
      <item>
        <title>Typing module in Python</title>
        <description>&lt;p&gt;Declaring &lt;code class=&quot;highlighter-rouge&quot;&gt;int&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;str&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;float&lt;/code&gt; variables is simple but declaring complex data types like List of tuples, List of dictionaries etc is cumbersome. This is where &lt;code class=&quot;highlighter-rouge&quot;&gt;typing&lt;/code&gt; module comes to rescue.&lt;/p&gt;

&lt;p&gt;The typing module in Python 3.6 contains many definitions that are useful in statically typed code.&lt;/p&gt;

&lt;p&gt;Here’s how to use the typing module in Python 3:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;from typing import Tuple, List, Dict

data: Tuple[int, str, List[int]] = (3, &quot;Python&quot; [1, 2, 3])
x: Dict[str, float]  = {'field': 2.0}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As generator function is also a function that returns an Iterable, here’s how to type annotate it :&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;from typing import Iterable
def f(n: int) -&amp;gt; Iterable[int]:
    i = 0
    while i &amp;lt; n:
        yield i
        i += 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Below snippet uses the Union type which is used to specify that the address argument can either be a string or a list of strings and the type Optional is specified for values that could be None.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;from typing import Union, Optional
def send_email(address: Union[str, List[str]],
               cc: Optional[List[str]
              ) -&amp;gt; bool: ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here’s how to type annotate Python 2 code using comments :&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;from typing import Tuple, List, Dict, Optional, Union, Iterable

data = (3, &quot;Python&quot; [1, 2, 3]) # type: Tuple[int, str, List[int]]
x = {'field': 2.0} # type: Dict[str, float]
def f(n: int):
    # type: (int) -&amp;gt; Iterable[int]
    i = 0
    while i &amp;lt; n:
        yield i
        i += 1
def send_email(address, # type: Union[str, List[str]],
               cc,      # type: Optional[List[str]
              ):
# type: (...) -&amp;gt; bool
...

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;using-type-aliases&quot;&gt;Using Type aliases&lt;/h2&gt;

&lt;p&gt;Type aliases can be defined by using simple variable assignments. It’s generally used when the type gets lengthier. In below exampleExampleType can be referenced at all places where the variable data is used.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ExampleType = Tuple[int, str, List[int]]
data: ExampleType = (3, &quot;Python&quot; [1, 2, 3])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;creating-your-own-types&quot;&gt;Creating your own types&lt;/h2&gt;

&lt;p&gt;In Python 3.5 a new function is introduced in typing called NewType. This allows you to create distinct types. The static type checker will treat the new type as if it were a subclass of the original type. You may still perform all int operations on a variable of type UserId, but the result will always be of type &lt;code class=&quot;highlighter-rouge&quot;&gt;int&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;One of the best use cases of mypy is that it helps in self documenting code to an extent. Some of the large code bases can be tough to read. It’s difficult to tell what a function or a class accepts. Type hinting would help in adding clarity and readability to code.&lt;/p&gt;

&lt;p&gt;Awesome folks at Dropbox built a Pycharm plugin that type checks and highlights the errors in the file.&lt;/p&gt;

&lt;p&gt;For more information about mypy and typing I would recommend reading their official documentation. And for folks starting on type hinting their Python projects I would recommend reading this blog where Tim Abbott detailed how Zulip started with and implemented type hinting.&lt;/p&gt;
</description>
        <pubDate>Tue, 21 Aug 2018 00:00:00 +0000</pubDate>
        <link>http://www.thabraze.me/2018/08/python-meta-classes.html</link>
        <guid isPermaLink="true">http://www.thabraze.me/2018/08/python-meta-classes.html</guid>
        
        <category>python</category>
        
        
      </item>
    
      <item>
        <title>Mypy - Optional static typing for Python - Part 1</title>
        <description>&lt;p&gt;Mypy  is an experimental static type checker for Python. As Python is a dynamically typed language, mypy aims to combine the benefits of dynamic typing and static typing.&lt;/p&gt;

&lt;p&gt;In other words, mypy is like a linter that scans your code and prints out errors if there are any type conflicts.&lt;/p&gt;

&lt;h2 id=&quot;role-of-pep-484&quot;&gt;Role of PEP-484&lt;/h2&gt;
&lt;p&gt;PEP-484 introduced the standard of type annotations (type hints) in Python. This standard came into existence from Python 3.5. This proposal adds syntax to Python for annotating the types of variables including class and instance variables.&lt;/p&gt;

&lt;p&gt;If you’re using Python 3.5 or greater, you can write function definitions as shown below&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def func(argv: Optional[Sequence[str]]) -&amp;gt; None: ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In the above snippet, the term after &lt;code class=&quot;highlighter-rouge&quot;&gt;:&lt;/code&gt; represents the type of the parameter and the term after -&amp;gt; represents the return type of the function.&lt;/p&gt;

&lt;p&gt;With the addition of PEP-484, Python 3.5 gained two things:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;A standard for describing types&lt;/li&gt;
  &lt;li&gt;A syntax support for annotating function arguments and the return values.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that we know about type annotations, but what exactly is type checking?&lt;/p&gt;

&lt;p&gt;Inspection of code to enforce that arguments and assignments match their declared types is known as &lt;em&gt;type checking&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Python 3.5 introduced type annotations but it didn’t come with built-in type checking. Core developers left the role to be filled by third party tools.&lt;/p&gt;

&lt;p&gt;There are handful of tools that perform PEP-484 compatible type checking and &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt; is one of them.&lt;/p&gt;

&lt;p&gt;Annotation syntax for function declarations in Python 3 is as shown below&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def plus(num1: int, num2: int) -&amp;gt; int:
    return num1 + num2
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To check Python 3 code against &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt;, run the command &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy program.py&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since type annotations were introduced in Python 3, for code that needs to be Python 2.7 compatible, function type annotations are given in comments as shown below. This syntax is also valid in Python 3 mode.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def plus(num1, num2):
    # type: (int, int) -&amp;gt; int
    return num1 + num2
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To check Python 2 code against &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt;, run mypy in Python 2 mode using the &lt;em&gt;— py2&lt;/em&gt; option.&lt;/p&gt;

&lt;h2 id=&quot;using-mypy&quot;&gt;Using Mypy&lt;/h2&gt;

&lt;p&gt;When a script is run with a standard Python interpreter, the type annotations are treated primarily as comments. As &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt; is a static analyzer, it does not cause any overhead when running the program.&lt;/p&gt;

&lt;p&gt;Let’s take a look at a simple example:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def function(number: int, name: str) -&amp;gt; None:
	print(&quot;%s entered %s&quot; % (name, number))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Above function takes in two parameters one of the type &lt;code class=&quot;highlighter-rouge&quot;&gt;int&lt;/code&gt; and other of type &lt;code class=&quot;highlighter-rouge&quot;&gt;str&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we call the function as &lt;code class=&quot;highlighter-rouge&quot;&gt;function(4, “John”)&lt;/code&gt; and run &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt;, issuing the command &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy program.py&lt;/code&gt;, we get no errors or warnings. So the provided type annotations are correct.&lt;/p&gt;

&lt;p&gt;However if we call the above function as &lt;code class=&quot;highlighter-rouge&quot;&gt;function(“4&quot;, “John”)&lt;/code&gt; and run &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt;, it throws an error saying error: Argument 1 to “function” has incompatible type “str”; expected “int”&lt;/p&gt;

&lt;p&gt;Using &lt;code class=&quot;highlighter-rouge&quot;&gt;mypy&lt;/code&gt;, common code bugs can be found and it checks the code for proper arguments and return types.&lt;/p&gt;

&lt;p&gt;Remember that a function without a type annotation is considered dynamically typed.&lt;/p&gt;
</description>
        <pubDate>Mon, 23 Jul 2018 00:00:00 +0000</pubDate>
        <link>http://www.thabraze.me/2018/07/mypy-optional-static-typing-for-python.html</link>
        <guid isPermaLink="true">http://www.thabraze.me/2018/07/mypy-optional-static-typing-for-python.html</guid>
        
        <category>python</category>
        
        
      </item>
    
  </channel>
</rss>
