🌐
Reddit
reddit.com › r/python › python true static typing
r/Python on Reddit: Python true static typing
May 21, 2023 -

Is it possible that static typing will ever be implemented in python, or does the current design make static typing impossible ?

🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original, which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost. Added in version 3.5.2. Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function. Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.
Discussions

Please, stop pushing for static typing in Python
We don't need static typing, we need other, much more useful things. Like stability, reliability, speed and good packaging standards · I don't want ugly Rust-like typing in my favorite language. It may look good in Rust, but it looks horrible in Python More on news.ycombinator.com
🌐 news.ycombinator.com
27
22
February 2, 2022
Python 3 and static typing - Stack Overflow
I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from this SO answer function parameter More on stackoverflow.com
🌐 stackoverflow.com
Python true static typing
Even though type hints are available at runtime and can be inspected for type validation (Pydantic and FastAPI take advantage of this, for example), I find it highly unlikely that Python will ever become statically typed. It is more likely that other Python implementations could emerge with such a typing model. Meta has a heavily modified version of CPython 3.10 called Cinder they use on Instagram. It has lots of experiments like static typing, strict modules, JIT compiler and much more: https://github.com/facebookincubator/cinder More on reddit.com
🌐 r/Python
51
25
May 21, 2023
How to type hint dictionaries without using Any?
Normally I'd suggest using typing.TypedDict, but that only works if the keys are valid identifiers. What's with all the @-symbols in the keys? More on reddit.com
🌐 r/learnpython
16
4
February 28, 2024
🌐
DEV Community
dev.to › saranshabd › python-w-strict-typechecker-3l7g
Python w/ strict typechecker - DEV Community
December 23, 2022 - “typing” in Python3.x is a suggester rather than a strict type checker.
🌐
Justin A. Ellis
jellis18.github.io › post › 2023-01-15-advanced-python-types
Some Advanced Typing Concepts in Python - Justin A. Ellis
January 15, 2023 - Well if you don't, it basically means that users of your code should not be forced to rely on interfaces/types/classes that they don't need. We will see how Python type annotations can help with this. First lets look at how we can make our code more robust by defining loose types for input parameters and strict types for outputs.
🌐
Hacker News
news.ycombinator.com › item
Please, stop pushing for static typing in Python | Hacker News
February 2, 2022 - We don't need static typing, we need other, much more useful things. Like stability, reliability, speed and good packaging standards · I don't want ugly Rust-like typing in my favorite language. It may look good in Rust, but it looks horrible in Python
🌐
Mypy-lang
mypy-lang.org
mypy - Optional Static Typing for Python
Mypy is an optional static type checker for Python.
🌐
Pyrefly
pyrefly.org › blog › why-typed-python
Why Today’s Python Developers Are Embracing Type Hints | Pyrefly
August 19, 2025 - Variables can hold any type of value, and you don't need to declare what type they are. ... This behaviour is one of the things that sets Python apart from languages that are statically typed, like Java or C++, which require you to declare types from the get go:
Find elsewhere
🌐
Medium
leapcell.medium.com › from-duck-typing-to-strict-types-pythons-evolving-type-system-09df4f5205f0
From Duck Typing to Strict Types: Python’s Evolving Type System | by Leapcell | Medium
May 31, 2025 - Weak Typing: Strong type systems strictly prohibit operations with mismatched types (e.g., Python does not allow direct computation of "3" + 5); weak type systems allow implicit type conversion (e.g., in JavaScript, "3" + 5 is automatically ...
🌐
Python
typing.python.org › en › latest › guides › typing_anti_pitch.html
Reasons to avoid static type checking — typing documentation
The idea that dynamism in Python ... that Python’s type system is gradual. See PEP 483 for details, but the long and short of this is that you can add static types to your codebase only to the extent that you want to, and static type checkers and other tools should be able to put up with this. It’s also worth noting that “static type checking” encompasses a spectrum of possible degrees of strictness...
Top answer
1 of 5
34

Thanks for reading my code!

Indeed, it's not hard to create a generic annotation enforcer in Python. Here's my take:

'''Very simple enforcer of type annotations.

This toy super-decorator can decorate all functions in a given module that have 
annotations so that the type of input and output is enforced; an AssertionError is
raised on mismatch.

This module also has a test function func() which should fail and logging facility 
log which defaults to print. 

Since this is a test module, I cut corners by only checking *keyword* arguments.

'''

import sys

log = print


def func(x:'int' = 0) -> 'str':
    '''An example function that fails type checking.'''
    return x


# For simplicity, I only do keyword args.
def check_type(*args):
    param, value, assert_type = args
    log('Checking {0} = {1} of {2}.'.format(*args))
    if not isinstance(value, assert_type):
        raise AssertionError(
            'Check failed - parameter {0} = {1} not {2}.'
            .format(*args))
    return value

def decorate_func(func):    
    def newf(*args, **kwargs):
        for k, v in kwargs.items():
            check_type(k, v, ann[k])
        return check_type('<return_value>', func(*args, **kwargs), ann['return'])

    ann = {k: eval(v) for k, v in func.__annotations__.items()}
    newf.__doc__ = func.__doc__
    newf.__type_checked = True
    return newf

def decorate_module(module = '__main__'):
    '''Enforces type from annotation for all functions in module.'''
    d = sys.modules[module].__dict__
    for k, f in d.items():
        if getattr(f, '__annotations__', {}) and not getattr(f, '__type_checked', False):
            log('Decorated {0!r}.'.format(f.__name__))
            d[k] = decorate_func(f)


if __name__ == '__main__':
    decorate_module()

    # This will raise AssertionError.
    func(x = 5)

Given this simplicity, it's strange at the first sight that this thing is not mainstream. However, I believe there are good reasons why it's not as useful as it might seem. Generally, type checking helps because if you add integer and dictionary, chances are you made some obvious mistake (and if you meant something reasonable, it's still better to be explicit than implicit).

But in real life you often mix quantities of the same computer type as seen by compiler but clearly different human type, for example the following snippet contains an obvious mistake:

height = 1.75 # Bob's height in meters.
length = len(sys.modules) # Number of modules imported by program.
area = height * length # What's that supposed to mean???

Any human should immediately see a mistake in the above line provided it knows the 'human type' of variables height and length even though it looks to computer as perfectly legal multiplication of int and float.

There's more that can be said about possible solutions to this problem, but enforcing 'computer types' is apparently a half-solution, so, at least in my opinion, it's worse than no solution at all. It's the same reason why Systems Hungarian is a terrible idea while Apps Hungarian is a great one. There's more at the very informative post of Joel Spolsky.

Now if somebody was to implement some kind of Pythonic third-party library that would automatically assign to real-world data its human type and then took care to transform that type like width * height -> area and enforce that check with function annotations, I think that would be a type checking people could really use!

2 of 5
15

As mentioned in that PEP, static type checking is one of the possible applications that function annotations can be used for, but they're leaving it up to third-party libraries to decide how to do it. That is, there isn't going to be an official implementation in core python.

As far as third-party implementations are concerned, there are some snippets (such as http://code.activestate.com/recipes/572161/), which seem to do the job pretty well.

EDIT:

As a note, I want to mention that checking behavior is preferable to checking type, therefore I think static typechecking is not so great an idea. My answer above is aimed at answering the question, not because I would do typechecking myself in such a way.

🌐
Python
typing.python.org › en › latest › spec › concepts.html
Type system concepts — typing documentation
In Python’s type system, we don’t take the gradual guarantee as a strict requirement, but it’s a useful guideline.
🌐
GitHub
github.com › typeddjango › awesome-python-typing
GitHub - typeddjango/awesome-python-typing: Collection of awesome Python types, stubs, plugins, and tools to work with them. · GitHub
pydantic - Data parsing using Python type hinting. Supports dataclasses. pytypes - Provides a rich set of utilities for runtime typechecking. strongtyping - Decorator which checks whether the function is called with the correct type of parameters. typedpy - Type-safe, strict Python.
Author: typeddjango
🌐
CodeBasics
code-basics.com › programming › python course › strong (or strict) typing
CodeBasics | Strong (or Strict) Typing | Python
You have to first either make the string a number or the number a string. We'll talk about how to do that later. This pedantic attitude towards type compatibility is called strict typing or strong typing.
🌐
Infrahub
docs.infrahub.app › python sdk docs › strict typing in python
Strict Typing in Python | Infrahub Documentation
Python Protocols, introduced in PEP 544, define a set of method and property signatures that a class must implement to be considered a match, enabling structural subtyping (also known as "duck typing" with static checks). They allow you to specify behavior without requiring inheritance, making code more flexible and type-safe.
🌐
YouTube
youtube.com › watch
"How to Use Static Typing in Python with Type Hints, MyPy and Pydantic" - Jack Bennett (PyOhio 2024) - YouTube
Jack Bennetthttps://www.pyohio.org/2024/program/talks/is-python-your-type-of-programming-languagePython's dynamic typing system famously offers flexibility,
Published: August 10, 2024
🌐
YouTube
youtube.com › watch
MyPy for Beginners: Getting Started with Static Typing in Python - YouTube
Here's a beginners guide on how you can get setup with MyPy, and dive into the world of static typing in Python!My beginners Python course:https://www.udemy....
Published: June 21, 2024
🌐
Thib
thib.me › python-static-type-checking-field-test
Python static type checking: field test - Thibaud’s blog
Research whether types are suitable on your project – do you have major dependencies that might be untyped and hard to stub? Are there JSON-like data structures that will need special attention to be typed correctly? Set up mypy with the most permissive settings possible. We can turn on the strictness later.
🌐
FastAPI
fastapi.tiangolo.com › python-types
Python Types Intro - FastAPI
By declaring types for your variables, editors and tools can give you better support. This is just a quick tutorial / refresher about Python type hints. It covers only the minimum necessary to use them with FastAPI...
🌐
Pydantic
docs.pydantic.dev › 2.2 › usage › types › strict_types
Types/strict types | Pydantic Docs
Besides the above, you can also have a FiniteFloat type that will only accept finite values (i.e. not inf, -inf or nan). from pydantic import BaseModel, FiniteFloat, StrictInt, ValidationError class StrictIntModel(BaseModel): strict_int: StrictInt class Model(BaseModel): finite: FiniteFloat try: StrictIntModel(strict_int=3.14159) except ValidationError as e: print(e) """ 1 validation error for StrictIntModel strict_int Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float] """ m = Model(finite=1.0) print(m) #> finite=1.0