this post was submitted on 16 Mar 2026
23 points (100.0% liked)

Python

7856 readers
2 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 

For example:

class FooBar:
    def __init__(self):
        self.a: int = None
        self.foo: str = None

Is this bad practice/go against PEP guidelines or is it fine?

top 9 comments
sorted by: hot top controversial new old
[–] joyjoy@lemmy.zip 23 points 2 weeks ago (1 children)

Implicit optional is deprecated. Explicitly use self.foo: int | None = None

[–] AstroLightz@lemmy.world 3 points 2 weeks ago

Thanks! Good to know.

[–] jtrek@startrek.website 8 points 2 weeks ago (1 children)

That seems like that's going to give you an error in most type checkers. You said it's always an int and then immediate made that a lie and made it None instead.

Why are you trying to do this?

[–] AstroLightz@lemmy.world 2 points 2 weeks ago

I'm initializing variables that would be used later in the class in different functions. I wasn't sure if I needed to do a var: <type> | None = None or if just setting it to None was fine.

[–] sbv@sh.itjust.works 3 points 2 weeks ago (1 children)

Why not require values in the constructor?

[–] AstroLightz@lemmy.world 2 points 2 weeks ago

This is an example. For my actual use case, they would be private vars that would be set by class functions instead of passed to the constructor.

[–] Vulwsztyn@programming.dev 2 points 2 weeks ago* (last edited 2 weeks ago)

yes, bad practice; yes, against PEP

[–] logging_strict@programming.dev 2 points 2 weeks ago* (last edited 2 weeks ago)

As can surmise from my handle, i'm even stricter!

Use Union, not | or Optional where ever possible.

Optional does not allow for future expansion of the typing. Optional[int] and then want to add float, so have to rewrite it Union[int, float, None] So write it with Union to begin with.

Went thru my | stage like everyone else, but grew out of it.

TypeAlias insists on Union, not |

So Union everywhere ftw

Why? If there is a possibility of making a mistake, Murphy's law dictates that it'll occur every damn time. Enough already! KISS principle is in effect.

[–] logging_strict@programming.dev 1 points 2 weeks ago* (last edited 2 weeks ago)

While we are on da topic, always use string notation! My experience, this was really non-obvious.

With both cast and typing. With cast, can let builtin types, like str or int, be passed in without the string notation.

This reduces the typing imports bleeding into your runtime code modules and tests.