On 7/29/19 10:44 AM, Michael F. Stemper wrote:
On 28/07/2019 19.04, Chris Angelico wrote:
On Mon, Jul 29, 2019 at 9:48 AM Michael Torrie <torr...@gmail.com> wrote:
On 7/28/19 5:55 AM, Jonathan Moules wrote:
But this appears to be explicitly called out as being "Worse" in PEP8:
"""
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
"""
Yet the recommended solution to the problem of wanting a default
argument of an empty list is something like this:
def foo(bar=False);
if bar is False:
bar = []
....
Clearly in this case the expression "not bar" would be incorrect.
This is a fairly unusual case, though. More commonly, the default
would be None, not False, and "if bar is None:" is extremely well
known and idiomatic.
That's certainly how I would have done it until I read your post. But
reading it immediately raised the question of why not:
def foo( bar=[] ):
if len(bar)==0:
print( "Pretty short" )
else:
print( bar )
return
Seems to work just fine.
Works find right up until you do anything that modifies bar, and find that bar
always points not to a new empty list each time but to the same empty list on
each call.
>>> def foo(bar=[]):
... bar.append(5)
... return bar
...
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
As far as ways to shoot one's own foot in Python, this is one of the most
common.
--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order. See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list