Type Checking Python

A Problem

  • It creates a Resource object given a bytes and a tuple of MetadataItem objects as parameters
  • Based on the usage, it appears that the Resource object’s read_metadata method returns a Dict[str, MetadataItem] object
  • Finally, it passes the Dict[str, MetadataItem] to the has_name function and prints its return value (in this case True)
$ python -m untyped
Traceback (most recent call last):
File "/Users/jtucker/.pyenv/versions/3.10.0/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/Users/jtucker/.pyenv/versions/3.10.0/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/Users/jtucker/src/learning/typedlearning/untyped/__main__.py", line 4, in <module>
run()
File "/Users/jtucker/src/learning/typedlearning/untyped/main.py", line 18, in run
print(has_name(metadata))
File "/Users/jtucker/src/learning/typedlearning/untyped/main.py", line 7, in has_name
return 'name' in metadata
TypeError: argument of type 'NoneType' is not iterable

Type Checking to the Rescue

$ mypy  -p typed --strict
typed/main.py:21: error: Argument 1 to "has_name" has incompatible type "Optional[Dict[str, MetadataItem]]"; expected "Dict[str, MetadataItem]"
Found 1 error in 1 file (checked 4 source files)

A Bonus

--

--

--

Broad infrastructure, development, and soft-skill background

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Writing the First Tests for a New Python Project

Does a mechanical keyboard make you a better developer?

Getting to the Good Stuff

Repeated validation could mean it’s time for an object rather than a primitive

How good metadata supports data pipelines

bunq API Anatomy: Transactions and Payments

Jupyter SQL Magic Connection to Redshift using IAM Credentials

Cucumber for BDD: Is the juice worth the squeeze?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
John Tucker

John Tucker

Broad infrastructure, development, and soft-skill background

More from Medium

The Python Vulnerability Landscape

How To Time Threaded Python Loops Efficiently

Rough Bug w/ Python Code

What is a type hint in Python?