Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's because your type is Optional[TypeOfVar] though; if you try using that variable in a place that expects just TypeOfVar before it's set, you should get an error.


Let me restate. To prevent ugliness in typing, either

* Python should have a way of declaring variables without setting them to None, so we can type hint them to their actual types. Pre-declaration is very important for a prototyping language, and needs to be done in a way that the variable is visible to dir().

* Come up with a cleaner syntax than the wordy Optional[]. Thankfully, they have recently moved on from the ugly Union[a,b] to the more readable a | b. Something more readable could be done for Optional.


but Optional[foo] is literally a union of foo | None already!


    a: int

    b: str | None = None


Right, in langs with c-style scoping, this is an issue, but in python

    if foo:
        x = a
    else:
        x = b
Works, so there's no need to predeclare.


A very common pattern in python is to declare all instance variables of a class in the __init__ method by setting them to None. This is done for

* code readability; all relevant variables are in one place

* Python is a prototyping language, and a very common usage pattern is doing dir(object) to determine the names of all variables that could be set to something.


This is no longer needed with modern python, you can use

    class Foo:
        my_int: int

To handle this. That said, for the second case, a variable that may be set to something but may not be is optional! That's correct behavior!




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: