r/Python • • Jul 12 '26

Discussion Will PEP 505 ever be accepted?

https://peps.python.org/pep-0505/

I don't understand how null safe operators are less like plain English than other implemented features like the walrus operator.

In my opinion, the member access operator would make python significantly easier to read and understand.

Here's an example:

f = foo()

if f is None:
    baz = ""
else:
    baz = f.bar()
baz = foo()?.bar() ?: ""

EDIT: I forgot that "and" and "or" can be sometimes used in place of "?." and "?:" if the left value is not False, '', 0, [], or {}. It's a very implicit null check and has a lot of unexpected behavior.

15 Upvotes

192 comments sorted by

View all comments

61

u/sausix Jul 12 '26

We have that functionality basically. It's a bit off standard and you have to be aware about the object's reported bool state.

baz = f and f.bar() or ""

Of course it's not beginner friendly but once you know about the magic behind and and or then you love it.

70

u/Designer-Ad-2136 Jul 12 '26

Or i'd do: baz = "" if f is None else f.bar()

28

u/k0pernikus Jul 13 '26

I rather see

f = foo()
if f is None:
    raise ValueError("Value cannot be None")

baz = f.bar()

or have a helper like:

def get_or_raise[T](v: T | None) -> T:
    if v is None:
        raise ValueError("Value cannot be None")
    return v

These implicit None to "" will come to bite you eventually.

4

u/Designer-Ad-2136 Jul 13 '26

True, that is an important consideration, especially as code scales. As with most coding solutions it is all context dependent. I'd tend towards that with time but i doubt id do that in a one-off script.

3

u/necromenta Jul 13 '26

Help I’m too stupid to understand the helper, the first example is clear as water to me tho

5

u/k0pernikus Jul 13 '26 edited Jul 19 '26

It looks scarier than it is. [T] is a generic (think of it as a placeholder for a type), so you can reuse the same helper for different types without having to repeat code.

It takes some getting used to, but is one of the most powerful feature any typesystem can have.

I think my example (stemming from stackoverflow) is a bit too loose btw. To actaully get better typesafety one has to do this:

def get_or_raise[T](v: T | None) -> T:
    if v is None:
        raise ValueError("Value cannot be None")
    return v

def create_get_or_raise[T](expected_type: type[T]):
    def inner(v: object) -> T:
        if not isinstance(v, expected_type):
            raise TypeError(f"Expected {expected_type.__name__} but got {type(v).__name__}")
        return v
    return inner

get_int_or_raise = create_get_or_raise(int)

print(get_int_or_raise(1337))

try:
    print(get_int_or_raise("1337"))
except TypeError as e:
    print(e)

try:
    get_int_or_raise(None)
except TypeError as e:
    print(e)

It will print:

1337
Expected int but got str
Expected int but got NoneType


** Process exited - Return Code: 0 **

Here it helps to also play around with other languages to see how they solve things.

While I hate scala with a passion, its type system is extremely powerful and I do miss some of its feature like compile-time extension (think of it as typesafe monkeypatching; e.g. adding methods on on collection types of an object was awesome! Yet also delving into TypeScript helped a lot. (PHP will hurt your understanding. And I say that as someone that started professional programming with PHP, and built some great products with it.)

Python is on this weird mixture where it is dynamaic and strongly typed; and the older I get, the more I love static and strongly typed approaches.

I also recommend delving into functional programming, its concepts play well with typed languages and it really boosted my game, e.g. the concept of pure functions (easily unit-testable), immutability (also great for unit-testing but also generally avoids nasty surprises), and higher-ordered functions (fancy word for saying: function that returns a function).

Hope this helped.

→ More replies (3)

4

u/sausix Jul 12 '26

Same effect. More beginner friendly. Personally I can read and understand f and f.bar() faster.

5

u/Nekomancerr Jul 12 '26

In nominal cases yes, but one is a truthiness check while the other is a None check. For example a str value of empty string would behave differently

4

u/Designer-Ad-2136 Jul 12 '26

Yeah, i dont mind that way either. id do something like that in my own personal code for longer chains as long as i can give it a good name. 

6

u/learn-deeply Jul 12 '26

not the same effect at all, False != None.

3

u/sausix Jul 12 '26

Of course. You're right. f and f.bar() is less explicit on checking for None. You can expand that with better and explicit checks but then it's getting out of readability again because of parantheses etc.

28

u/Due_Campaign_9765 Jul 12 '26

Now chain 5 of them.

15

u/timrprobocom Jul 12 '26

No, don't do that. Impossible to read. Python has historically eschewed improvements that do nothing but save keystrokes.

10

u/Due_Campaign_9765 Jul 12 '26

I'm not choosing to do or not to do that, there are often APIs that have everything as nullable.

There is simply not a good way to do that in python. Most of the time I reach towards try/catch which is insane.

7

u/double_en10dre Jul 12 '26

Yeah 100%, it’s something that makes a LOT of sense if you have to ingest external data.

Being able to drill down n-levels without throwing errors or losing type hints is massively beneficial for any language that glues services together. And ya, Python is one of those languages

The alternative is a mess of try/catch or endless chained “.get(key, {})” calls. Which is garbage code

2

u/thaynem Jul 14 '26

IMHO

    foo()?.bar()?.a?.b?.c

Is a lot easier to read than

    bar  = f and f.bar()
    a= bar and bar.a
    b = a and a.b
    c = b and b.c

Or using a bunch of ifs.           

2

u/_redmist Jul 13 '26

With some braces that is quite feasible.

1

u/cottonycloud Jul 13 '26

IMO the initial example the commenter provided is already unreadable and turns to shit if you have to chain once more.

1

u/sausix Jul 12 '26

What do you mean?

f and f.bar()

and

f and f.bar() or "Value on None"

cover a lot of simple None checks already.

Web scraping (bs4) for example has a lot of chained statements which can all be None and break value retrieval. While it introduces a lot of member access cycles it still can just be chained with and operators as one liner.

12

u/Due_Campaign_9765 Jul 12 '26

x.foo().bar().baz().quux().iranoutofcliches()

Every step is nullable.

There is no clear way to access the deepest variable, expect maybe try/catch. But that's an insane way to program.

1

u/sausix Jul 12 '26

Thanks for the example. At that point a try/catch is not too bad. Exception handling is not forbidden.

How do other programming languages solve this?

That foo()?.bar() syntax is probably very rare.

Some syntaxes missing in Python can be solved with Python too. If you really want that conditional chaining you could create a class to solve and allow this:

result = NullShield(obj, "value on None").foo().bar()

Pick a better name as NullShield if you like.

3

u/Due_Campaign_9765 Jul 12 '26

Other languages use the proposed here null-safe operators and/or strict type checking.

You can do anything you'd like, it just looks terrible.

Exceptions are terrible for perfomance and makes a regular null check into an something exceptional, which it's no. Not to mention it spans 4 lines. That's exactly how you're not supposed to use them.

4

u/sausix Jul 12 '26

If you are concerned about having 4 lines then make use of a context manager.

I never said try/except is elegant or fast.

My point is that you can build a lot of functionalities with standard Python. Same as the recurring wishes for Python having the feature for chaining functions. It can be done today with little effort but within current syntax rules. So there is no reason to expand the Python syntax.

The walrus operator was already a big concern. It just saves a line.

→ More replies (2)
→ More replies (2)

4

u/Zubzub343 Jul 14 '26

If I see this in a production code-base I will immediately git blame and track the person who wrote that.

This is classic Python beginner (actually 90% of python dev who claim to be developers) thinking they are clever doing some "codegolf" one-liner and not understanding the countless number of ways this statement can go wrong. Even worse, they're gonna scream proudly the word "Pythonic" which is the most BS expression ever seen in programming.

It all boils down to implicit conversion to bool, which is sin (looking at you Javascript) but the problem is that many "not None" values convert into False.

That said, in this specific example I guess it works </rant>

→ More replies (1)

4

u/philtrondaboss Jul 13 '26

I know that, but they aren't exclusive to None. They also catch {}, [], 0, '', and False.

→ More replies (3)