jtmoulia, to emacs
@jtmoulia@mstdn.social avatar

A guide on integrating + + using [mostly] builtin tooling and project local .dir-locals.el variables.

Specifically, this setup uses + for live syntax checking, for code running, for type-checking, and as the shell

Feedback would be welcome -- trying to get it robust + idiomatic.

https://jtmoulia.srht.site/guides/emacs-python-hatch/

chrisyxlee, to python
@chrisyxlee@hachyderm.io avatar

TIL in my adventures, the proper way to set up a class that returns itself is to use the Self typing annotation and return values by calling self.__class__ on the new value

from typing import Self  
class ImActuallyAString(str):  
 def one_longer(self) -> Self:  
 return self.__class__(self + "one")  

ᕕ( ᐛ )ᕗ (please tell me if I'm wrong lol)

mistersql, to random
@mistersql@mastodon.social avatar

Okay, I'm ready to sell ad space in the type annotations of my open source code.

from typing import TypeAlias

SquareSpaceChooseYourCanvas: TypeAlias = str  
SquareSpaceSuccessStory: TypeAlias = str

def build_website(self, template: SquareSpaceChooseYourCanvas) -> SquareSpaceSuccessStory:  
 """  
 Your Ad Here, call 1-800-doc-string  
 """  
 print(f"Building a website with the template '{template}'.")  
 return "Wee!"  
CyrilBrulebois, to random
@CyrilBrulebois@mamot.fr avatar

This feeling when you search for answers, find people with the same questions, who wrote about possible solutions (not once but twice!), but their website is not responding…

https://nedbatchelder.com/blog/202302/late_initialization_with_mypy.html
https://nedbatchelder.com/blog/202302/late_initialization_reconsidered.html

Poke @nedbat ;)

CyrilBrulebois,
@CyrilBrulebois@mamot.fr avatar

@nedbat I couldn't find a cached version (quite probably I didn't look hard enough).

In my case, the offending part was:

class Foo:
bar: Bar = None

Tried:

class Foo:
bar: Optional[Bar] = None

This makes happy in that spot, but then I would have needed to disambiguate the type (via asserts and the like) all the time, so I went for something simple yet not entirely satisfactory:

class Foo:
bar: Bar = None # type: ignore

And everything else expects bar to be Bar, not None.

nobodyinperson, to python
@nobodyinperson@fosstodon.org avatar

I'm always fascinated how amazing the :python: #Python standard library is.

itertools, collections, dataclasses, subprocess, unittest, logging, argparse, pathlib, json, re, shlex [the list goes on] are all so incredibly useful and you can rely on them as they're always there (paying attention to versioning of course).

And with type hints and #mypy I guess I can stay with just Python for a little longer 😉

glyph, to python
@glyph@mastodon.social avatar

PEP 593 is a bit vague on how you’re supposed to actually consume arguments to Annotated; here is my proposal.

https://blog.glyph.im/2023/12/annotated-at-runtime.html

blong, to python
@blong@fosstodon.org avatar

In addition to using , can anyone share any guidance, tooling, or blogs that may help steer a application towards the "TypeState" pattern? I'm also curious if there are references comparing the "State" pattern to the "TypeState" pattern (Rust).

I suppose I'm looking specifically for Python comparisons with , e.g. if there were a part 2 for the article here:

https://kobzol.github.io/rust/python/2023/05/20/writing-python-like-its-rust.html

Forgive my ignorance, I'm trying to learn 😬

cc/ @adamchainz @davidfstr

sourcenouveau, to python
@sourcenouveau@fosstodon.org avatar

Does mypy not do type inference when you use functions from other modules? That can't be right...

If I have:

modabc.py

def abc() -> str:  
 return "abc"  

modxyz.py

from modabc import abc

def xyz() -> str:  
 x = abc()  
 return x  

I get error: Returning Any from function declared to return "str".

I would prefer not to annotate the local variable. How come mypy isn't checking the annotations from modabc?

folkerschamel, to python
@folkerschamel@mastodon.social avatar

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

This unsolved challenge bugs me:
How can I add type hints to the following 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 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)

ado, to python

I am really excited for 3.12 for three reasons.

First reason - No more ugly TypeVar declarations.

Old generic type:

from typing import Generic, TypeVar<br></br><br></br>_T_co = TypeVar("_T_co", covariant=True, bound=str)<br></br><br></br>class ClassA(Generic[_T_co]):<br></br>    def method1(self) -> _T_co:<br></br>        ...<br></br>

New generic:

class ClassA[T: str]:<br></br>    def method1(self) -> T:<br></br>        ...<br></br>

Second reason: 🚀 Gotta go fast. From the abstract

Comprehensions are currently compiled as nested functions, which provides isolation of the comprehension’s iteration variable, but is inefficient at runtime. This PEP proposes to inline list, dictionary, and set comprehensions into the code where they are defined, and provide the expected isolation by pushing/popping clashing locals on the stack.

Last: F Strings will support some common use cases that broke interpolation in the past, like f'{ myDict['myKey'] }' and f"{'n'.join(a)}"

Full notes: https://www.python.org/downloads/release/python-3120b3/

cazabon,

@folkerschamel @ado

Asking for specific type checking finds is ... unproductive. You write 2 modules of code, run , 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.

[...]

folkerschamel,
@folkerschamel@mastodon.social avatar

@cazabon @ado

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

alebaffa, to python
folkerschamel,
@folkerschamel@mastodon.social avatar

@FSMaxB @alebaffa

No we don't use . But it requires type hints, right? So we cannot use it anymore.

We would have to add type hints to a lot of existing code.

kellogh, to python
@kellogh@hachyderm.io avatar

hot take: dynamic languages like and would benefit a lot by a little type checking around async/await constructs — simply emitting a compiler error (or even a warning) when you don’t await an async function call would save massive amounts of time

orsinium,
@orsinium@fosstodon.org avatar

@kellogh In , 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.

partizan, to python

Turns out using func(**kwargs)becomes very inconvinient, when you're using type-checking.

Pyright 1.1.312 landed a change:

> ... The new behavior matches that of mypy and assumes that the unpacked dict may supply arguments for all otherwise-unmatched keyword parameters even if they have default argument values.

https://github.com/microsoft/pyright/issues/5545

And now i need # type: ignore for each **kwargs.

@hynek any ideas how to approach this?

Or maybe someone on the ?

partizan,

@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

jamescooke, (edited ) to python
@jamescooke@fosstodon.org avatar

🧠 A new tool where I:

1. pick my Python version 👈 Edit: Don't need this actually (thanks @orsinium)

  1. type in what I want

... And it tells me if I should be using an Enum, Dataclass or NamedTuple 😬 or even installing attrs and using that.

orsinium,
@orsinium@fosstodon.org avatar

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

_alen, to python

At first, I didn’t like type hints in , but we decided to give it a go since our codebase really exploded in the last couple of years. All I can say now is we should have done it earlier. I still find it unbealivable that we discovered so many small bugs that went unnoticed all these years.

_alen,

@Stark9837 I totally understand. In our case, including in CI pipeline made us more disciplined.

orsinium,
@orsinium@fosstodon.org avatar

@folkerschamel @_alen I have plenty of examples! I'm integrating with a 400k LoC 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.

ambv, to python
@ambv@mastodon.social avatar

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

understands them just fine.

pawamoy, to random
@pawamoy@fosstodon.org avatar

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

pawamoy, to random
@pawamoy@fosstodon.org avatar

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

adamchainz, to python
@adamchainz@fosstodon.org avatar

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

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

ethantyping, to python
@ethantyping@hachyderm.io avatar

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!

mistersql, to programming
@mistersql@mastodon.social avatar

Oh, nice. Better syntax for typing generics in

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.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • megavids
  • thenastyranch
  • magazineikmin
  • cubers
  • InstantRegret
  • cisconetworking
  • Youngstown
  • vwfavf
  • slotface
  • Durango
  • rosin
  • everett
  • kavyap
  • DreamBathrooms
  • provamag3
  • mdbf
  • khanakhh
  • modclub
  • tester
  • ethstaker
  • osvaldo12
  • GTA5RPClips
  • ngwrru68w68
  • Leos
  • anitta
  • tacticalgear
  • normalnudes
  • JUstTest
  • All magazines