60
you are viewing a single comment's thread
view the rest of the comments
[-] sugar_in_your_tea@sh.itjust.works 8 points 4 days ago* (last edited 4 days ago)

len(mylist) tells me it’s definitely a list and not null or whatever

Do you know what else can tell you it's a list? Type hinting.

If I care about the distinction between None and an empty list, I'll make separate checks. len(None) raises an exception, and most of the time that's not what I want when checking whether there's something in the list, so not x is generally preferred, especially when type hinting is used consistently enough to be reasonably sure I'm actually getting a list or None. If I get something else, that means things got really broken and they'll likely get an exception alter (i.e. when doing anything list-like).

For sequence type objects, such as lists, their truth value is False if they are empty.

That's generally exactly what I want. len(x) == 0 doesn't tell you it's a list, it just tells you it has __len__. So that could be a dict, list, or a number of other types that have a length, but aren't lists.

Don't rely on checks like that to tell you what type a thing is.

this post was submitted on 24 Apr 2025
60 points (94.1% liked)

Python

7049 readers
54 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