Live data from Hacker News

Python Idioms [pdf]

safehammad.com

81–90 of 128 posts

Re: Python Idioms [pdf]

#81
i agree with all but #2. this seems to embrace conciseness as simplicity or understandability. it forgets the more cardinal value that explicit is better than implicit.

Re: Python Idioms [pdf]

#82
post #76

Earlier 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.

In this particular situation, there was no else. I probably added an else clause with an assert return_value == False, as the function call was a virtual dispatch that could have many implementations. Of course, I wouldn't do that for every if/then/else statement in my code. In general, I'd prefer a stricter language that only permitted a boolean as a condition in the IF statement, avoiding this problem altogether.

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]

#83

Although 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…

What level would you say the idioms in the book are at? I have already been programming in python for a little while, and I wouldn't want to pay for something which I already know. It would be nice if there were more sample idioms on that site so you could have a better idea of what the rest of the book was like.

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)

I prefer

  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]

#85

Interesting 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…

I understand it exactly.

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]

#86
post #79

Interesting 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…

owners is a non-empty set.

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]

#88
post #34

Earlier 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.

> `len` blows up on None, so this blows up completely instead of just failing

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]

#89
post #33

I 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.

Not to mention how awesome they become when you feed them as a set of values to a function.

    values = (f(x) for x in list)
    g(*values)

Re: Python Idioms [pdf]

#90
post #74
post #72

Earlier 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))

The original use for that code was to build a list of parsing objects to create a single parsing object that was the OR'ing of the basic ones.

Aw, heck, code speaks louder than words:

https://github.com/PhoenixBureau/PigeonComputer/blob/master/...

Post reply on HN