avatarLiu Zuo Lin

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3026

Abstract

can customise Mypy’s behaviour using a configuration file named <code>mypy.ini</code> or <code>.mypy.ini</code> in your project's root directory. Some useful configuration options include:</p><ul><li><code>strict</code>: Enables strict mode, which enforces stricter type checking.</li><li><code>ignore_missing_imports</code>: Ignores missing imports instead of raising an error.</li><li><code>disallow_untyped_defs</code>: Disallows functions without type annotations.</li></ul><p id="3e5e">An example configuration file might look like this:</p><div id="36e3"><pre><span class="hljs-section">[mypy]</span> <span class="hljs-attr">strict</span> = <span class="hljs-literal">True</span> <span class="hljs-attr">ignore_missing_imports</span> = <span class="hljs-literal">True</span> <span class="hljs-attr">disallow_untyped_defs</span> = <span class="hljs-literal">True</span></pre></div><h1 id="2960">Step 5: Integrate Mypy into Your Workflow</h1><p id="1a0e">To make Mypy an integral part of your development process, consider integrating it with your favourite code editor or IDE. Many editors, such as VSCode, PyCharm, and Sublime Text, have plugins or built-in support for Mypy.</p><p id="dc60">Note — if your Python script doesn’t follow the type hints, Python will still allow it to run. Mypy, on the other hand, will catch the error for you.</p><h1 id="5694">A Positive Example — Mypy in action</h1><div id="9ad2"><pre><span class="hljs-comment"># test.py</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">a:<span class="hljs-built_in">int</span>, b:<span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">int</span>: <span class="hljs-keyword">return</span> a + b

x = add(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>) <span class="hljs-built_in">print</span>(x)</pre></div><div id="aa4b"><pre>mypy test.py

<span class="hljs-comment"># Success: no issues found in 1 source file</span></pre></div><p id="8aea">Here, we use <code>mypy</code> on a Python script that follows its type hints — the <code>add</code> function takes in 2 integer values, and we respect that in the function call.</p><h1 id="d3c1">A Negative Example — Mypy in action</h1><div id="dd7a"><pre><span class="hljs-comment"># test.py</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">a:<span class="hljs-built_in">int</span>, b:<span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">int</span>: <span class="hljs-keyword">return</span> a + b

x = add(<span class="hljs-string">'4'</span>, <span class="hljs-string">'5'</span>) <span class="hljs-built_in">print</span>(x)</pre></div><div id="2053"><pre>mypy test.py

<span class="hljs-comment"># b.py:4: error: Argument 1 to "add" has incompatible type "str"; expected "int" [arg-type]</span> <span class="hljs-comment"># b.py:4: error: Argument 2 to "add" has incompatible type

Options

"str"; expected "int" [arg-type]</span> <span class="hljs-comment"># Found 2 errors in 1 file (checked 1 source file)</span></pre></div><p id="a08e">Here, the <code>add</code> function takes in 2 integers <code>a</code> and <code>b</code>, but we pass in 2 string values into <code>add</code>, ignoring the type hints.</p><p id="4cf4">If we run the Python script itself, it will still work! This is because Python itself does not enforce the type hints. However, if we run it through <code>mypy</code>, it catches us not respsecting the type hints, and thus informs us about it.</p><h1 id="0aff">Conclusion</h1><p id="5f47">Mypy is a powerful tool that can enhance your Python development experience by catching type-related errors early and promoting cleaner, more robust code. By integrating Mypy into your workflow, you can create more maintainable and reliable software that’s easier to collaborate on. Give Mypy a try and experience the benefits for yourself!</p><h1 id="63a1">Some Final words</h1><p id="831a"><i>If this story provided value and you wish to show a little support, you could:</i></p><ol><li><i>Clap 50 times for this story (this really, really helps me out)</i></li><li><i>Sign up for a Medium membership using <a href="https://zlliu.medium.com/membership">my link</a> ($5/month to read unlimited Medium stories)</i></li></ol><p id="f191"><b>My Home Office Setup: <a href="https://zlliu.co/workspace">https://zlliu.co/workspace</a></b></p><p id="2a40"><b>My Free Ebooks: <a href="https://zlliu.co/books">https://zlliu.co/books</a></b></p><div id="0ef0" class="link-block"> <a href="https://zlliu.medium.com/subscribe"> <div> <div> <h2>Get an email whenever Liu Zuo Lin publishes.</h2> <div><h3>Get an email whenever Liu Zuo Lin publishes. By signing up, you will create a Medium account if you don't already have…</h3></div> <div><p>zlliu.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*aw47UOrssb62dMSl)"></div> </div> </div> </a> </div><h1 id="c326">Level Up Coding</h1><p id="97c8">Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev">Newsletter</a></li></ul><p id="052a">🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><b>Join the Level Up talent collective and find an amazing job</b></a></p></article></body>

Mypy — Static Type Checking In Python In 4 Minutes

# Supercharge Your Python Development

Python’s dynamic typing makes it an easy-to-use and flexible language, but it also can lead to bugs that only surface at runtime. Mypy, a static type checker, offers a solution by analysing your code for type-related issues before it is executed.

What is Mypy?

Mypy is an open-source, optional static type checker for Python that can help you catch type-related errors before your code is executed. It uses the type hints introduced in Python 3.5 (PEP 484) to analyse your code, verify the correctness of types, and highlight inconsistencies or errors. With Mypy, you can write more robust and maintainable Python code.

Benefits of Using Mypy

  1. Catch Errors Early — Mypy identifies type-related issues during development, reducing the likelihood of runtime bugs.
  2. Improve Code Quality — Mypy enforces consistent type usage, promoting cleaner and more reliable code.
  3. Enhance Readability — Type hints used by Mypy make your code more explicit and easier to understand.
  4. Boost Collaboration — Mypy ensures your code adheres to type annotations, making it more accessible to other developers and facilitating better teamwork.

Let’s get started with using Mypy.

Step 1 — Install Mypy

pip install mypy

Step 2 — Add Type Hints to Your Code

Before Mypy can check your code, you need to add type hints using the typing module. Here’s a simple example:

from typing import List

def greet_users(usernames: List[str]) -> None:
    for username in usernames:
        print(f"Hello, {username}!")

Step 3 — Run Mypy on Your Code

To analyze your code with Mypy, run the following command:

mypy your_script.py

Mypy will report any type inconsistencies or errors it finds in your code.

python -m mypy your_script.py

^ alternative command if the above doesn’t work

Step 4 — Configure Mypy (Optional)

You can customise Mypy’s behaviour using a configuration file named mypy.ini or .mypy.ini in your project's root directory. Some useful configuration options include:

  • strict: Enables strict mode, which enforces stricter type checking.
  • ignore_missing_imports: Ignores missing imports instead of raising an error.
  • disallow_untyped_defs: Disallows functions without type annotations.

An example configuration file might look like this:

[mypy]
strict = True
ignore_missing_imports = True
disallow_untyped_defs = True

Step 5: Integrate Mypy into Your Workflow

To make Mypy an integral part of your development process, consider integrating it with your favourite code editor or IDE. Many editors, such as VSCode, PyCharm, and Sublime Text, have plugins or built-in support for Mypy.

Note — if your Python script doesn’t follow the type hints, Python will still allow it to run. Mypy, on the other hand, will catch the error for you.

A Positive Example — Mypy in action

# test.py

def add(a:int, b:int) -> int:
    return a + b

x = add(4, 5)
print(x)
mypy test.py

# Success: no issues found in 1 source file

Here, we use mypy on a Python script that follows its type hints — the add function takes in 2 integer values, and we respect that in the function call.

A Negative Example — Mypy in action

# test.py

def add(a:int, b:int) -> int:
    return a + b

x = add('4', '5')
print(x)
mypy test.py

# b.py:4: error: Argument 1 to "add" has incompatible type "str"; expected "int"  [arg-type]
# b.py:4: error: Argument 2 to "add" has incompatible type "str"; expected "int"  [arg-type]
# Found 2 errors in 1 file (checked 1 source file)

Here, the add function takes in 2 integers a and b, but we pass in 2 string values into add, ignoring the type hints.

If we run the Python script itself, it will still work! This is because Python itself does not enforce the type hints. However, if we run it through mypy, it catches us not respsecting the type hints, and thus informs us about it.

Conclusion

Mypy is a powerful tool that can enhance your Python development experience by catching type-related errors early and promoting cleaner, more robust code. By integrating Mypy into your workflow, you can create more maintainable and reliable software that’s easier to collaborate on. Give Mypy a try and experience the benefits for yourself!

Some Final words

If this story provided value and you wish to show a little support, you could:

  1. Clap 50 times for this story (this really, really helps me out)
  2. Sign up for a Medium membership using my link ($5/month to read unlimited Medium stories)

My Home Office Setup: https://zlliu.co/workspace

My Free Ebooks: https://zlliu.co/books

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

Python
Python Programming
Programming
Coding
Recommended from ReadMedium