Giter Site home page Giter Site logo

python-typing-koans's Introduction

Python-typing-koans

A set of examples to learn optional static typing in Python.

asciicast

Install

  • Install Python 3.9.4+.

  • Install poetry - https://python-poetry.org/docs/#installation .

  • Clone the repository and change the directory to the cloned one.

  • Install requirements like poetry install.

  • If you want to use pip, pip install -r requirements.txt.

Idea

One of the best ways to learn python-typing is to annotate the code. In this repo, koans directory contains a set of files which will teach you python type-hints by fixing errors. The files carry a suffix from 100 in the increasing order. By solving errors in the each file in the increasing suffix order, you will gain knowledge about Python hints. It starts with simple variable annotation and covers topics function annotation, generics, protocols, classes.

How to learn?

The existing files has no annotations or wrong annotation, as a learner, you run one file and fix each errors till there are no type-errors. In the next section, you will learn, how to list all koans and how to run the modified koan file.

All the koan files are present in the following directories

koans/py
koans/dj_koans/mysite/polls/koans

How to run?

  • Display one koan file
$cat koans/py/100-easy-variable-wrong-type.py
# msg variable is wrongly annotated as int, annotate it as string
msg: int = "hello world!"

# salary is annotated as int, annotate as float
salary: int = 2345.67

# Set is_active as bool
is_active: int = True
  • Run one koan file
$poetry run python cli.py one koans/py/100-easy-variable-wrong-type.py
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Running Mypy on koan file koans/py/100-easy-variable-wrong-type.py
──────────────────────────────────  Mypy errors in koan file koans/py/100-easy-variable-wrong-type.py ───────────────────────────────────
koans/py/100-easy-variable-wrong-type.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int")
    msg: int = "hello world!"
               ^
koans/py/100-easy-variable-wrong-type.py:5: error: Incompatible types in assignment (expression has type "float", variable has type
"int")
    salary: int = 2345.67
                  ^
Found 2 errors in 1 file (checked 1 source file)

────────────────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────────────────
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  • Run after fixing the errors(riddles) in the file.
$poetry run python cli.py one koans/py/100-easy-variable-wrong-type.py
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Running Mypy on koan file koans/py/100-easy-variable-wrong-type.py
No errors in koan file koans/py/100-easy-variable-wrong-type.py 👍
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  • List all files: poetry run python cli.py list
$poetry run python cli.py list
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
koans/py/100-easy-variable-wrong-type.py
koans/py/101-easy-tuple-value.py
koans/py/102-easy-list-homogenous.py
koans/py/103-easy-mixed-values.py
koans/py/104-easy-union-example.py
koans/py/105-easy-dictionary-example.py
koans/py/106-easy-function-example.py
koans/py/107-easy-typed-dict.py
koans/py/108-easy-type-alias.py
koans/py/109-easy-user-defined-class.py
koans/py/110-easy-class-variable.py
koans/py/111-medium-callable-annotate.py
koans/py/112-medium-type-as-example.py
koans/py/113-easy-builder-pattern.py
koans/py/114-medium-factory-pattern.py
koans/py/115-medium-protocol-covariant-dbapi-example.py
koans/py/116-easy-factory-example.py
koans/py/117-easy-protocol-across-objects.py
koans/py/118-medium-protocol-behave-like-dict.py
koans/py/119-medium-queue-genrics.py
koans/py/120-medium-decorator.py
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  • Print summary of all koan files.
$poetry run python cli.py summary
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 Ran mypy in koan file: koans/py/100-easy-variable-wrong-type.py 👍
 Ran mypy in koan file: koans/py/101-easy-tuple-value.py 👎
 Ran mypy in koan file: koans/py/102-easy-list-homogenous.py 👎
 Ran mypy in koan file: koans/py/103-easy-mixed-values.py 👎
 Ran mypy in koan file: koans/py/104-easy-union-example.py 👎
 Ran mypy in koan file: koans/py/105-easy-dictionary-example.py 👎
 Ran mypy in koan file: koans/py/106-easy-function-example.py 👎
 Ran mypy in koan file: koans/py/107-easy-typed-dict.py 👎
 Ran mypy in koan file: koans/py/108-easy-type-alias.py 👎
 Ran mypy in koan file: koans/py/109-easy-user-defined-class.py 👎
 Ran mypy in koan file: koans/py/110-easy-class-variable.py 👎
 Ran mypy in koan file: koans/py/111-medium-callable-annotate.py 👎
 Ran mypy in koan file: koans/py/112-medium-type-as-example.py 👎
 Ran mypy in koan file: koans/py/113-easy-builder-pattern.py 👎
 Ran mypy in koan file: koans/py/114-medium-factory-pattern.py 👎
 Ran mypy in koan file: koans/py/115-medium-protocol-covariant-dbapi-example.py 👎
 Ran mypy in koan file: koans/py/116-easy-factory-example.py 👎
 Ran mypy in koan file: koans/py/117-easy-protocol-across-objects.py 👎
 Ran mypy in koan file: koans/py/118-medium-protocol-behave-like-dict.py 👎
 Ran mypy in koan file: koans/py/119-medium-queue-genrics.py 👎
 Ran mypy in koan file: koans/py/120-medium-decorator.py 👎
  Koans Summary
┏━━━━━━━━┳━━━━━━━┓
┃ Status ┃ Count ┃
┡━━━━━━━━╇━━━━━━━┩
│ Passed │ 1     │
│ Failed │ 20    │
└────────┴───────┘
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Resource for learning Python type-hints

Supported Koans

  • Python - koans/py
  • Django - koans/dj_koans/mysite/polls/koans
  • Django Rest Framework - koans/dj_koans/mysite/polls/drf_koans

How to contribute?

  • If you feel, some examples will make a great learning material, add a new file in the format 1xx-<easy|medium|hard>-filename.py and send a PR.
  • If you feel some of the koan file is missing enough links or not well-defined please send a PR or raise an issue.
  • If you feel some of the concepts needs a better examples or missing, open a PR or create an issue.

To Support

  • Add async example koans
  • Add third party annotation koans like django, DRF in separate sub-directory in koans/.

python-typing-koans's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

python-typing-koans's Issues

Python Typing Koans: Solutions

Hey!

Thank you for creating this repository and responding so swiftly over chat. This set of Koans helped me to better understand type hints in Python

There were some sections in which my solutions seemed a little hacky and would like to know how others have solved it and how I might improve my own solutions. I'm still working on the koans and there are about 6 Koans left to be done though. Will resume working on this tomorrow.

Here are my solutions: https://github.com/J0/python-typing-koans

Thanks again! This is a great repo.

112-medium-type-as-example discussion

It look like this example has to be rewritten in the following manner (snippet is typed):

# Annotate the resp_klass as the type of response class
# Documentation: https://docs.python.org/3/library/typing.html?highlight=typing#typing.Type
def make_response(data: JSONData, resp_klass: Type[JSONResponse] = JSONResponse) -> bytes:
    return resp_klass(data).make_response()

I guess that in this case the code has some meaning.
Also the is an unused import Union from typing.

103-easy-mixed-values discussion

The comments mention another way of typing the solution. My solution is as follows:

"""
Koan to learn annotating the Python list of various type of elements
"""
from typing import Union, List
# Annotate mixed type-values. There are two-ways to annotate this
nos: list[Union[int, float]] = [1, 2.0, 3.5]

# Annotate the list of int to list of better types
squares: list[Union[int, float]] = [no * no for no in nos]

I suppose this could be one way to annotate. Would just like to check what the other way is.

114-medium-factory-pattern

Hey @kracekumar,

Thanks for taking the time to reply to all my past queries. I'm a little stuck on 114 and was wondering if you could provide a hint or suggestion of sorts. I'm currently using overloaded method signatures for sock_type in the following format:

@overload
def _sock_type(addr: Tuple[str,int])-> Union[TCPSocket,TCP6Socket]:...
@overload
def _sock_type(addr: Union[str, bytes])-> UnixSocket:...


def _sock_type(addr: Address):
      <implementation details>

However, this solution still uses union and unfortunately it also means that sock_type in the line below is TCP Socket, TCP6Socket or Unix Socket whic produces the type error sock_type is not callable.

sock = sock_type(address, conf, log)

Was wondering if you have any hints/suggestions/tips.

Let me know

`dry-python` koans: `returns` and `classes`

My might say that dry-python/returns is one of the most typing-intensive project in Python-land.
It might be a good idea to add some expert-level koans about it. Like:

classes can also be useful if one wants to work with typeclasses in Python: https://sobolevn.me/2021/06/typeclasses-in-python

I don't have the timing capacity to contribute this myself, but I would love to help 🙂

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.