Python Idioms [pdf]
81–90 of 128 posts
Re: Python Idioms [pdf]
#82Earlier quoted context omitted.
I've personally run into problems when I don't do exact comparisons with True and False. For example, I've forgotten to return a value in one path of a function/method, and then tried to use the result in an if statement in the style recommended by the OP (e.g. if fcall(): do something). After being bitten several times by this, I always do explicit comparisons.
So you never use "else"? Else is the mother of inexact comparisons.
If you are using truthy/falsey values, I think it can be a code smell that you are not doing enough to catch invalid values up front or should normalize the values closer to their creation point.
Re: Python Idioms [pdf]
#83Although many of them boil down to preferences and philosophical points of view, I find these kinds of idioms useful. Whenever I write code in a new language, I want to "write as a native" so that I can maximize the effect that the language has on how I think about programming. For Python in particular, Jeff Knupp's "Writing Idiomatic Python"[1] (not free, but not expensive, either) goes into detail on a lot of the c…
Re: Python Idioms [pdf]
#84>pets = ['Dog', 'Cat', 'Hamster'] >for pet in pets: > print('A', pet, 'can be very cute!') This may be nit picking but I prefer output like this: print 'A %s can be very cute!' %(pet)
print("A {0} can be very cute!".format(pet))
.format() is very versatile. d = {'first': 'Robert', 'last': 'Paulson'}
print("His name was {first} {last}!".format(**d))
>> His name was Robert Paulson!
class Person:
def __init__(self, first, last):
self.first, self.last = first, last
p = Person('Robert', 'Paulson')
print("His name is {0.first} {0.last}!".format(p))
>> His name was Robert Paulson!
You also do not need to know what type is being passed in as the __str__ method is used for .format().Re: Python Idioms [pdf]
#85Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…
Really? Containers of different types have a len method; which type of container is pets? The line you wrote doesn't tell you. And is owners supposed to be a set? If so, your comparison to an empty dict will give the wrong semantics if owners is an empty set (owners != {} will return True for an empty set, not False). You would have to write
len(owners) > 0
to get the correct semantics. Which, of course, already obscures the type of owners, just as the type of pets is obscured.In short, your suggested "improvement" over idiomatic Python still obfuscates rather than clarifying.
Re: Python Idioms [pdf]
#86Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…
It's a dynamic-typing thing. In some hypothetical static-strong-non-duck version of Python, if name != '' and len(pets) > 0 and owners != {} would tell you that name is a non-empty string, pets has values, and owners is a non-empty dict (except it doesn't work, as pdonis noticed). But Python allows immoral implicit conversions, so that's not what that line means! If name is a function, pets is the value '7' and owner…
No, it doesn't tell you that. {} denotes an empty dict, not an empty set; and an empty set will return True for owners != {}, not False. As I noted in another post upthread, you would need to write
len(owners) > 0
to get the correct semantics, making owners indistinguishable from pets even if they are different container types. If you really wanted to make all the types clear, you would need to include the isinstance tests.Re: Python Idioms [pdf]
#87His last slide could be written more idiomatically as ''.join('Thanks!')
set('abcd')
idiom.Re: Python Idioms [pdf]
#88Earlier quoted context omitted.
Checking for empty strings can be done with len(mystring)==0 for this reason. In many other languages this method is standard and recommended practice. Relying on implicit conversions is just sloppy. What if that variable was never supposed to be None in the first place. Better with an exception than continuing with corrupt data. Remember another python motto: Explicit is better than implicit.
> Checking for empty strings can be done with len(mystring)==0 for this reason. `len` blows up on None, so this blows up completely instead of just failing. > Relying on implicit conversions is just sloppy. There is no implicit conversion. Truthiness is a protocol, it does not convert anything anywhere.
That's the whole point! As I said, Better with an exception than continuing with corrupt data. Or maybe I should say unsupported data type rather than corrupt data.
Re: Python Idioms [pdf]
#89I would add generator expressions: (f(x) for x in list_of_inputs) Just like a list comprehension, but with (...) rather than [...] and with lazy evaluation. These are useful when you don't need to evaluate all of the inputs at once but still want to iterate over them at some point later on.
values = (f(x) for x in list)
g(*values)Re: Python Idioms [pdf]
#90Earlier quoted context omitted.
Yeah, I realized after posting it. (See edit.) The original code was using non-string objects. I basically come up with this to get the same behavior as str.join(). ;-)
'|'.join(str(x) for x in y) # or '|'.join(map(str, y))
Aw, heck, code speaks louder than words:
https://github.com/PhoenixBureau/PigeonComputer/blob/master/...