r/Python • • Jul 22 '21

Resource Do not use mutable objects as default arguments in Python

https://medium.com/geekculture/do-not-use-objects-as-default-arguments-in-python-1c940212db2e
1.3k Upvotes

218 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Jul 22 '21

[deleted]

10

u/jelly_cake Jul 23 '21

Interesting to note that Python actually has a ternary syntax too:

some_var = "foo" if (condition) else "bar"

IMO, while this maps somewhat more naturally to how we'd read it, it's still just as confusing as C's syntax. I like chaining with it slightly better though.

some_var = (condition)? "foo" : "bar";

2

u/TheTerrasque Jul 23 '21

you could also do

some_var = condition and "foo" or "bar"

5

u/jelly_cake Jul 23 '21

Ooh, that's cool. It looks like it might do unexpected things if "foo" or "bar" were falsey expressions instead.

2

u/TheTerrasque Jul 23 '21

yes, if "foo" was false'y, it would return "bar". I sometimes use it to fill out data structures for API's where you need to send either string X or string Y depending on a condition, so in those cases it's not really a problem