skorokithakis / django-annoying

A django application that tries to eliminate annoying things in the Django framework. ⛺
http://skorokithakis.github.io/django-annoying
BSD 3-Clause "New" or "Revised" License
921 stars 87 forks source link

fix: Add type annotations to `get_object_or_None()` #104

Closed tylerlaprade closed 3 months ago

tylerlaprade commented 9 months ago

Fixes #103

Test plan

Pyright recognizes a Model type

image

Pyright rejects a non-model type

image

Pyright rejects an instance of a model in place of the type

image

Pyright accepts a BaseManager

image

Pyright accepts a QuerySet

image
skorokithakis commented 8 months ago

Sorry for the delay! Which versions does this work with? Would you mind changing the supported versions in the setup file?

tylerlaprade commented 8 months ago

Sure, happy to do that, ~just not sure where to look~!

EDIT: I found setup.py. It seems out of date, as the latest Python version it lists is 3.6, while the latest stable version is 3.12.2. Type hints were first introduced in 3.5, but were a bit clunky. If we want to continue supporting older versions, we might need to find some workarounds to get the older versions to ignore new syntax.

skorokithakis commented 8 months ago

I'm fine to drop support for older versions and only support 3.6+, but there's a specifier you use in the setup.py to tell it which Python versions you want to support, and I don't remember the syntax offhand. Would you happen to remember what I'm talking about?

tylerlaprade commented 8 months ago

As far as I can tell, 'Programming Language :: Python :: 3.XX', is all we need in setup.py.

However, I just tested and found that this simpler syntax for generic types only became available in Python 3.12. If we want to support 3.10 and 3.11, we'd have to change it to use the older TypeVar syntax, like so: T = TypeVar('T', bound=CondorBaseModel).

To go earlier than 3.9, we'd have to change the union type syntax of the return type from T | None to Union[T, None] (I'm still trying to confirm if this is right). This would give us 3.5-3.9.

To go all the way back to 3.0, we would simply have to replace from typing import TypeVar with from typing_extensions import TypeVar. If we're already making the switch to TypeVar, this wouldn't be a big deal.

I have not checked what it would take to maintain Python 2.0 compatibility, but I can look it up if desired.

image
skorokithakis commented 8 months ago

I think 3.5+ is fine, anything past that might be a bit too new. I don't mean the trove classifier, I meant the python_requires directive.

tylerlaprade commented 3 months ago

Hi, sorry for the delay, I was on paternity leave. I believe this addresses all the problems.