News for hackers. Stuff that matters.
Re:Python type hints may not be not for me in practice by ansgri on Wednesday November 27, 2024 @04:50PM (#42260153)
Why? I thought one should prefer immutability. As for typed dicts.. yes, I’m mostly stuck on old python versions, nice reminder.
Re:Python type hints may not be not for me in practice by maleldil on Wednesday November 27, 2024 @06:23PM (#42260822)
You can use TypedDict from `typing_extensions` if your version doesn't have it. You can use a lot of the newer stuff from there, too, especially if you enable `__future__.annotations`.

How old is your Python, though? TypedDict is from 3.8. That was 5 years ago.

Re:Python type hints may not be not for me in practice by throwaway2037 on Wednesday November 27, 2024 @09:09PM (#42261738)
You can use:

    > @dataclass(frozen=True)
to create an immutable data class.
Re:Python type hints may not be not for me in practice by maleldil on Thursday November 28, 2024 @06:38AM (#42264497)
While that works (and I use it extensively), it's a bit hacky. You have to use `object.__setattr__` to set attributes in `__init__` or `__post_init__`, which looks so wrong.
Re:Python type hints may not be not for me in practice by maxbond on Thursday November 28, 2024 @10:29PM (#42270558)
I think the cleaner alternative would be to use a static or class method as an alternative constructor and use the init the dataclass decorator provides for you. Eg something like:

    @dataclass(frozen=True)
    class Foo:
        bar: int
        baz: str

        @classmethod
        def new(cls, bar: int) -> "Foo":
            baz = calculate_baz(bar)
            return cls(bar, baz)

    foo = Foo.new(10)
Re:Python type hints may not be not for me in practice by throwaway2037 on Saturday November 30, 2024 @10:30AM (#42282099)
What is wrong with a static factory method?
Re:Python type hints may not be not for me in practice by int_19h on Friday November 29, 2024 @03:20PM (#42276773)
In general, preferring immutability is great. In Python specifically, it can be hard to pull off given that e.g. something as basic as dict does not have a standard immutable equivalent. You inevitably have to rely on conventions - basically saying "this is supposed to be immutable" rather than enforcing it.