Masthash

#mypy

ben
2 weeks ago

I am not enjoying the way #mypy can suddenly find new type errors in code that hasn't changed at all. #python

(but only in CI! so if i add a comment to ignore the ‘error’, local mypy — the same version — complains that the comment is unnecessary.)

mugnaini
3 weeks ago

Is there any *good* type-checker for python? But I really mean a good one... I had bad experiences with mypy being not smart enough and even pyre-check can't handle `Optional` types correctly (similar issue with mypy).

Should I just give up on trying to have a better experience with python and just accept the fact that it is an inherently bad language to type-check?

#python #mypy #pyre #typechecker #typehints

zenforyen
1 month ago

@zcutlip I'd claim it's a good thing #mypy made you learn these concepts, because I think everyone building complex labyrinths of data types and classes should understand how the puzzle pieces work 😉

Zachary Cutlip
1 month ago

Yesterday mypy forced me to learn about covariance, contravariance (and by extension invariance) in the context of programming language typing which isn't exactly what I signed up for, but it's hard to complain about learning new things so ¯\_(ツ)_/¯

https://github.com/zcutlip/pyonepassword/blob/07fb23dc3b381a711a90e93b88a00cdd6e107a72/pyonepassword/_op_cli_argv.py#L368C13-L368C13

#python
#mypy
#ComputerScience
#programming

Folker
1 month ago

@ketmorco @zenforyen @diazona @bk1e @askonomm @cazabon @ado @kevin

This unsolved challenge bugs me:
How can I add type hints to the following #python class

class D:
def __init__(self, t):
self._t = t
def __getattr__(self, n):
def m(*args):
print("a")
getattr(self._t, n)(*args)
print("b")
return m

so that #mypy can detect type bugs like the following?

class Q:
def f(self, x: int):
print(x)
q = Q()
d = D(q)
d.f(2.0)

Michał Górny
1 month ago

No więc dzisiaj aktualizuję #mypy do 1.5.1, i widzę, że nie ma żadnych zmian w kodzie, tylko zmiana numeru wersji. Mały CDF (co do faki?).

Teraz ztrawhcse gada mi na IRC-u, że przecież zmiany są:

https://github.com/python/mypy/compare/v1.5.0...v1.5.1

ja na to: no tak, czyżby nadpisali tag? Więc wymuszam ponowne pobranie, ale suma kontrolna się zgadza. Coraz większe CDF. Pobieram przez przeglądarkę, dostaję ten sam plik.

Wtedy ściągam 1.5.0… i mamy facepalm miesiąca. Nadpisali 1.5.0 na wcześniejszą wersję kodu już po tym, jak zaktualizowaliśmy paczkę w Gentoo.

Innymi słowy, użytkownicy Gentoo właściwie używali 1.5.1 już od tygodnia. Nie musicie nam dziękować.

#Python

Michał Górny
1 month ago

So I've bumped #mypy to 1.5.1 today, and I was surprised to see that the diff didn't include any changes aside from the version number change. A little WTF.

Now ztrawhcse tells me on IRC that there are changes, actually:

https://github.com/python/mypy/compare/v1.5.0...v1.5.1

So I'm like: oh my, did they force push? So I refetch 1.5.1 but checksum matches. I'm deep in WTF, I download again via browser, still the same file.

Then I refetched 1.5.0… and that's like facepalm of the month. They retagged 1.5.0 to an earlier commit after we've bumped it in #Gentoo.

Or to put it in other words, Gentoo users have been effectively running 1.5.1 for a week now. No need to thank us.

#Python

Folker
1 month ago

@zenforyen @askonomm @cazabon @kevin @ado

How would you express something like the following architecture in #mypy friendly #python code or even better in different programming languages like #cpp, #java, #golang etc?

(One part of our software is fundamentally based on countless such calls all over the place.)

def f(smart_evaluator, a, b):
...

def g(...):
x = smart_evaluator.exec(f, someting_extra, a, b)

Of course it is possible, but the question is how natural, easy and elegant it is.

Folker
1 month ago

@cazabon @ado

I just realize: As far as I understand #mypy, my previous #python Elastic Search example wouldn't be caught by #mypy because the parameter was passed to a logging function using formating via an f-string.

C.
1 month ago

@folkerschamel @ado

Asking for specific #examples type checking finds is ... unproductive. You write 2 modules of code, run #mypy, and get a list of the 11 places you need to fix - before you've even written unit tests that may or may not have caught the same problem.

If I tried to keep track of them all, I wouldn't have time to write code.

[...]

#TypeHints #TypeChecking #tests #lint

gram
2 months ago

@kellogh In #python, #mypy already reports not awaited functions that you don't assign anywhere. And if you do assign, you'll get a type error when you try to use it as a value instead of as a coroutine.

gram
2 months ago

@EMR @astraluma I know a few tools!

https://github.com/typeddjango/awesome-python-typing#testing

The difference in these tools is where you want to put your type tests: next to regular tests, in yaml, or in a separate Python file(s). The first approach is bad if you don't want to exclude all your tests from type checker. The second one is fine but you lose autocomplete and linters. I'm the author of the third way:

https://github.com/orsinium-labs/mypy-test

Also, basic tests are possible with just #mypy:

https://pythonetc.orsinium.dev/posts/assert-type

#python

Tin Tvrtković
2 months ago

You know it's going to be one of those days when you run #mypy on some code you've been writing and Mypy crashes on it.

What's even worse is that the crash is in the attrs plugin, so there's a chance it's actually my fault.

partizan
2 months ago

@ambv so, what do you think about this problem?

It also behaves the same way in mypy. But here bug is not closed, and i'm hoping it can be fixed.

https://github.com/python/mypy/issues/11583

#Python #PythonTyping #Mypy #Pyright

gram
2 months ago

@kevinbowen Is there a reason to go with #pyright and django-types instead of #mypy and django-stubs? IMHO, mypy is more powerful and django-stubs mypy plugin infers quite a few things for you. Plus, mypy-baseline can help a lot with integrating mypy with a big project.

I still use pyright in vscode but for autocomplete and stuff rather than type checking. And it has the django stubs out of the box.

partizan
2 months ago

#Python #PythonTyping #Pyright #Pylance #Mypy

Is there a way to create type stub only for part of the library?

For example: I want to include types for a single object, but don't want to maintain full copy of the library types.

https://github.com/carltongibson/django-filter/pull/1585/files

gram
2 months ago

@folkerschamel @_alen I have plenty of examples! I'm integrating #mypy with a 400k LoC #Django monolith (with a help of mypy-baseline), and it uncovers hell of a lot of bugs and bad design choices. The number one bag is, perhaps, a nullable Django model field (detected with django-stubs mypy plugin) that isn't checked for null. Something like this:

send_email(request.user.email, 'hi')

Which will explode if we don't check the user isn't anonymous and that they have an email address.

#python

gram
2 months ago

@jamescooke In #mypy, you can set your project #Python version, and it will tell you if you use something unsupported in this version.

Łukasz Langa
2 months ago

Anybody found a way to make the #Pylance type checker understand Click decorators?

#Mypy understands them just fine.

#Python #PyRight

A screenshot from VScode showing red squiggly lines below a @click.command() line with the Pylance error: "Untyped function decorator obscures type of function; ignoring decorator".

Is it me or #Mypy just got a whole lot faster? It feels like it runs as fast as #Ruff now! 😄

I really enjoy #mypy updates: transparent, regression-free, and each time it seems #mypy understands more things about my code, so I can remove some type-ignore comments. Kudos to #mypy's maintainers and contributors!

gram
3 months ago

@python_discussions That's not true. You need to specify `__all__` in `__init__.py` (and other facades) so that #mypy, #flake8, and #ruff know that these packages are imported to be exported. Then flake8 and ruff won't report unused import and mypy will allow reexports from the module.

#python

✍️ New post on some quality-of-life improvements in last week's Mypy release!

#Python #Mypy

https://adamj.eu/tech/2023/06/26/python-type-hints-modernized-error-messages-mypy-1.4.0/

gram
3 months ago

@glowrocks That's great! I'm glad to hear it empowers you to achieve your goals.

If you need guidance on more classic and reliable tools, just ask. In #python, I recommend to have a look at #ruff and #mypy, if you haven't already. These are good for finding simple errors without running the code. And Deal and Hypothesis should help with generating tests.

gram
3 months ago

@benc mypy will report it by default, unless the name you are trying to import is aliased in the proxy module using `as` or included in `__all__`:

https://mypy.readthedocs.io/en/stable/config_file.html#confval-implicit_reexport

#python #mypy

Ben Clifford
3 months ago

i guess i'm kinda interested that neither flake8 nor mypy noticed this...

#flake8 #MyPy

Tin Tvrtković
3 months ago

Just saw that there is now an official VSCode extension from Microsoft for using mypy.

https://marketplace.visualstudio.com/items?itemName=ms-python.mypy-type-checker

Very cool!

#python #mypy #vscode

Matthew Martin ☑ ✅📛
4 months ago

Oh, nice. Better syntax for typing generics in #python

https://peps.python.org/pep-0695/

I'll be able to use this in libraries that need to support old versions of python in about.... 1 trillion years.

#mypy

Worked like a charm, except it's called DefaultMeta now.

from flask_sqlalchemy import DefaultMeta, SQLAlchemy db = SQLAlchemy() Model: DefaultMeta = db.Model

And then import this Model and replace db.Model with Model everywhere.

With this mypy keeps working as you upgrade from flask-sqlalchemy 2 to flask-sqlalchemy 3. I haven't verified that the typechecking still detects type violations, only that it passes on our existing valid code.

#python #mypy #flask #SQLAlchemy #FlaskSQLAlchemy

@python

ottO
4 months ago

Anyone out there having to support more than one version of MyPy|TypeShed|mypy-extensions|python with the same codebase?

Even with having different .mypy.ini's sometimes the hints in the code are incompatable and you end up playing whack a mole.

For example, is it r: Redis or r: Redis[bytes] or Redis[str]?

#mypy #python

Marc Gibbons
4 months ago

An admission: I've been recalcitrant toward type annotations in #python since they were introduced (with the notable exception of dataclasses). I begrudgingly used them (w/ #mypy) in a recent project and slowly came around to it – led to catching a few AttributeError vulnerabilities around NoneType values. A bit of stumbling around pytest fixtures returning callbables at first.

Now that I'm working in a legacy codebase, I find myself missing them... #progress ?

scy
4 months ago

I _assumed_ this is because when given a list of files, #mypy handles each one separately, and if you create a file called csv.py (maybe even completely outside of any package whatsoever) and write something like

from csv import DictReader
print(DictReader)

into it, won’t #Python interpret `csv` as _your_ file instead of the standard library?

Turns out, no, it doesn’t. The code above works fine.

In that case I _really_ don’t understand what’s going on with mypy here.

scy
4 months ago

#mypy’s import handling is confusing.

While #Python itself lets me have a module named `csv` inside of a (sub)package (e.g. `convert/csv.py`), and that file can even successfully import the standard library’s _own_ `csv` module, mypy will tell me things like `myproject/convert/csv.py:21: error: Module has no attribute "DictReader"`.

This only happens when giving mypy a _directory_ of files to run on. If you instead run `mypy -p myproject` (i.e. on the _package_), it works. 🤔

Tin Tvrtković
4 months ago

While trying to figure out #Mypy docstring conventions to get a PR merged I discovered the Mypy developer guide: https://github.com/python/mypy/wiki/Developer-Guides. Looks like a great starting point for someone getting started with contributing. No docstring conventions mentioned though, I might add that once I work it out.
#python

Ben Clifford
5 months ago

Today the mine i am mining in is the regression-tests-that-are-disabled-because-they-stopped-passing mine.

(because #mypy is mad at the test now due to my on-going creeping static checking project)

It's testing a bit of code that I'm expecting new devs to be making significant changes to soon, so it's actually worth fixing...

Ben Clifford
5 months ago

dill vs ParamSpec - a battle I wasn't expecting, but apparently here I am.

#mypy #dill #serialization #python

Happy Monday! I am looking for work.

I am looking for a role related to compilers ideally, but I'm also capable in numerical computing and back-end roles. I have experience with #Rust 🦀 and #Python 🐍 .

I have a deep knowledge of Python from working on #mypy and CPython itself. The quantum compiler I worked on was a mixed Python/Rust codebase.

I'm looking for remote/hybrid near SF Bay Area.

Github: https://github.com/ethanhs

(boosts appreciated)

#fedijobs #getfedihired #fedihired #jobseeker

Guiguid
5 months ago

@python_discussions
#python : 3 dev tools, #mypy, #ruff and #black, to rule them all !

Csepp 🌢
5 months ago

Trying to track down some stupid type related error in some #Scheme code that a type checker would have caught.
Honestly #MyPy might be a bigger reason for why I often reach for #Python instead of Scheme than library availability.
Maybe I'd like #Racket with its gradual typing extensions, but it is significantly more resource hungry than Python.

Seth Michael Larson
6 months ago

#Mypy 1.2 adds support for native floats and integers to mypyc 👀

https://mypy-lang.blogspot.com/2023/04/mypy-12-released.html

#Python

A function which sums a list of "i64" types from mypy-extensions module representing 64-bit signed integer native types.
Ben Clifford
6 months ago

i am once again wrestling with decorator typing in python

#mypy #python

Juan Luis
6 months ago

Amusing to read this article from @passle about #TypeScript from a #Python perspective: https://dev.to/thepassle/using-typescript-without-compilation-3ko4

Looks like parts of the #JavaScript ecosystem are abandoning TypeScript and putting types in docstrings and header files.

Meanwhile, in Python we are going in the opposite direction: moving types from docstrings to signatures (making them hard to read, quite frankly), and giving up on using stubs because of #MyPy https://github.com/python/mypy/issues/5028

Could we do things differently? #DEVCommunity

What's currently the best way to check type annotations while running unit tests?!?

#mypy is nice, but not enough.

#python #unittest #typechecking

Ben Clifford
7 months ago

This One Neat Trick for python decorators (to give optional parameters to python) feels like it needs dependent types to put a type annotation on. or a typechecker plugin.

Ugh.

#Python #MyPy #DependentTypes

Theresa O’Connor
7 months ago

LazyActivityPub: could someone who understands Python type annotations tell me with small words what I'm doing wrong here? https://gist.github.com/hober/b1aa525e1e2bbca1ddeb12d43ba6090a #python #mypy #eli5

Just discovered while reading werkzeug's pyproject.toml that #mypy can read pyproject.toml "now"! (as of 0.900, June two years ago)

Guido was vehemently against that last time I checked (four years ago).

And it's not just a mypy.ini transplant, it's making use of toml to improve the parameter format. Nice!

@python #python
Ben Clifford
7 months ago

awww poor static typing all upset:

from typing import List, Union
a: Union[List[str], List[int]] = []

$ mypy myfoo.py
myfoo.py:2: error: Incompatible types in assignment (expression has type "List[<nothing>]", variable has type "Union[List[str], List[int]]") [assignment]
Found 1 error in 1 file (checked 1 source file)

#MyPy #Python #Types

Tin Tvrtković
7 months ago

In #Mypy 1.0, you can use `Final` attributes in #attrs classes and Mypy will know they are frozen instance attributes.

So if you use Mypy, this'll get you *overhead-free* frozen classes, but with a bunch of caveats:
* it doesn't work if the attribute has a default (any default), even like `attrs.field` or `attrs.Factory`
* the class won't be hashable by default

These are tricky to solve. The work continues. #python

Seth Michael Larson
8 months ago

The #Mypy project has reached a huge milestone, v1.0.0! 🥳 40% performance boost and a bunch of other improvements:

https://mypy-lang.blogspot.com/2023/02/mypy-10-released.html?m=1 #Python

Paolo Melchiorre
8 months ago

MyPy 1.0.0 has been released 🎉

"Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes." ✨

Some of them 👇
- the new version numbers will be of form x.y.z 🏷️
- version 1.0 is up to 40% faster than 0.991 ⚡
- it will now generate an error if you use a variable before it’s defined 🐛
- mypyc can now compile Python 3.10 match statements ✅

https://mypy-lang.blogspot.com/2023/02/mypy-10-released.html

#mypy #python #type #check

José A. Alonso
8 months ago

The comprehensive guide to MyPy. ~ Tushar Sadhwani (@sadhlife). https://sadh.life/post/mypy-guide #Python #MyPy

People out here sleepin' on mypyc.

http://mypyc.readthedocs.io/

#Python #mypy #mypyc

Ben Clifford
8 months ago

My back burner side project to get mypy and other type checking into @ParslProject is now explicitly enumerated in one of the grants that funds me, so I'm ramping up on slightly more aggressive rearrangement of code, now the almighty dollar has blessed me.

#MyPy #Python #StaticTyping

I like when I upgrade mypy and get to remove "unused type ignore comment" and "redundant cast" usages. Getting more accurate a little at a time. #python #mypy

Ed Rivas
10 months ago

Found a weird bug when using #mypy, #django REST Framework, and Django Filter. Any experts willing to take a look? https://github.com/typeddjango/djangorestframework-stubs/issues/299

Ben Clifford
10 months ago

ah the lolz that is `True` typechecks against a function that wants an `int` in Python, because bool is a subclass of int.

explodes my head about once a year

#mypy

Olivia Appleton
10 months ago

It's time for a re-#introduction!

I'm a #MastersStudent in #ComputerScience. In my spare time, I develop #OpenSourceSoftware such as
- a library to talk to #ManifoldMarkets from native #Python
- a #PredictionMarket manager using the above
- a transpiler from a subset of Python to #OpenStreetMaps's OverpassQL
- bug fixes to many other projects, including #mypy, #base58, #attrs, #cpython, and more

I'm also a hobbyist editor on OpenStreetMap.

#Bi, #transfem, and happily dating my enby sweetheart

Olivia Appleton
11 months ago

It's time for a re-#introduction!

I'm a #MastersStudent in #ComputerScience. In my spare time, I develop #OpenSourceSoftware such as
- a library to talk to #ManifoldMarkets from native #Python
- a #PredictionMarket manager using the above
- a transpiler from a subset of Python to #OpenStreetMaps's OverpassQL
- bug fixes to many other projects, including #mypy, #base58, #attrs, #cpython, and more

I'm also a hobbyist editor on OpenStreetMap.

#Bi, #transfem, and happily dating my enby sweetheart