Live data from Hacker News

Python Idioms [pdf]

safehammad.com

101–110 of 128 posts

Re: Python Idioms [pdf]

#101
post #90
post #74

Earlier quoted context omitted.

'|'.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/...

    intersperseM or $ map chartok whitespace
Oh... wait... sorry... wrong language.

Re: Python Idioms [pdf]

#102
The very first one, "Make a script both importable and executable," needs some caveats. It's useful sometimes, but people often use it in places where it is not a great idea. Here's why:

1) If you are in the mindset of "I want a single file which is both a library and a program," how will you name it? Files to import must end with ".py" and follow C-style name rules, so cannot start with a number cannot contain hyphens. This leads many people to break conventions when naming their programs, because on Unix, hyphens are conventional in program names but underscores are not (count the examples of each in /usr/bin on any system). And naming your program something like "2to3" is impractical if you want it to be importable also.

2) It is unclear where to install files which are both programs and libraries. Programs usually go in some sort of "bin" directory (again, on Unix systems), but libraries do not. Where do you put a file which is both?

3) Sometimes the __name__ == '__main__' trick is used to include unit tests within a module. That's not bad, but consider using Python's excellent doctest feature instead, which often serves the same need but in a richer way.

Re: Python Idioms [pdf]

#103
post #3

I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…

Not to counter your point, but I would like to quote from PEP8 here: Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs. Yes: try: value = collection[key] except KeyError: return key_not_found(key) else: return handle_value(value) No: try: # Too broad! return handle_value(collection[key]) except KeyError: # Will also catch K…

These two comments together make a lot of sense.

When your try block is a single lookup, you might as well use an if statement or get. However, when the 'absolute minimum' is nontrivial try/except is still a good option, e.g.

  try:
      name = employee['name']
      first_name = name['first_name']
      last_name = name['last_name']
  except KeyError:
      print "Bad employee data"
      return

Re: Python Idioms [pdf]

#104

The very first one, "Make a script both importable and executable," needs some caveats. It's useful sometimes, but people often use it in places where it is not a great idea. Here's why: 1) If you are in the mindset of "I want a single file which is both a library and a program," how will you name it? Files to import must end with ".py" and follow C-style name rules, so cannot start with a number cannot contain hyphe…

I use the __name__ == '__main__' thing for unit testing.

I don't know if this is a generally applicable technique, but a lot of my modules interact with hardware or physical measurements, so I have to "see" the results in order to believe that the units are working. Often, what I'm looking for is problems with what's actually being measured, and the effect of changing operating conditions, not just my own copious programming bugs.

For this reason, my unit tests can be pretty elaborate, with GUI, graphs, and other stuff. The unit test also functions as a "demo" of the module.

Re: Python Idioms [pdf]

#105
post #11

As a huge Python fan, I'm ashamed to admit but I don't get the while True: break What's the problem? I supose the use case is while True: # do stuff if some_condition: break What is the alternative? 'while some_condition'? That means we must have the 'some_condition' variable outside of the loop. And if we have multiple exit points it may become a mess.

Personally, because I find infinite loops to be a real PITA, I prefer to do: for _ in xrange(100000): break else: logging.error("ran into an infinite loop") unless I really do need an infinite loop for things like event handler loop, which is admittedly quite rare.

That seems incredibly silly, and looks like it could lead to very infrequent bugs (the worst kind). `while True` is shorter, simpler, and conveys the actual purpose better.

Maybe having a statement like that when testing is okay, but in production code that looks insane.

Re: Python Idioms [pdf]

#106
Another one that I find useful -- using `map` instead of list comprehensions when you want to apply a function to every element. So instead of:

    [str(x) for x in array]
Do this:

     map(str, array)

Re: Python Idioms [pdf]

#107
post #99
post #76

Earlier quoted context omitted.

So you never use "else"? Else is the mother of inexact comparisons.

Use the else to let you know that something is going wrong, using raise or exit() or some die() function: if something: do_this() elif something_else: do_that() else: # hope we don't end up here raise UserWarning('We shouldn't have ended up here')

But the discussion is about truthy values and inexact comparisons - avoiding inexact comparisons and having an else means:

    if something==True:
        do_this()
    elif something==False:
        do_that()
    else:
        raise UserWarning("Shouldn't be here")
Which is a code smell to me. What I would do is:

    assert isinstance(something, boolean), "Shouldn't happen"
    do_this() if something else do_that()
(replace assert with something else if you want it not to be optimized away with -O; assert is a debug-only construct in Python. Or just drop the assert altogether. In most places, I would - there's no end to the amount of validation you could do, and most of it is unnecessary)

Re: Python Idioms [pdf]

#108
post #3

I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…

what's going to happen in your second example if somebody gives you a defaultdict instead of a regular dict for d.

Re: Python Idioms [pdf]

#109

The very first one, "Make a script both importable and executable," needs some caveats. It's useful sometimes, but people often use it in places where it is not a great idea. Here's why: 1) If you are in the mindset of "I want a single file which is both a library and a program," how will you name it? Files to import must end with ".py" and follow C-style name rules, so cannot start with a number cannot contain hyphe…

I use the __name__ == '__main__' thing for unit testing. I don't know if this is a generally applicable technique, but a lot of my modules interact with hardware or physical measurements, so I have to "see" the results in order to believe that the units are working. Often, what I'm looking for is problems with what's actually being measured, and the effect of changing operating conditions, not just my own copious pro…

Absolutely--that's a great example of a library module that may also be usefully executed. I had something similar today: a module that sends email. It's useful to be able to run it (by explicit "python foo.py", not chmod +x) and see a sample email in my inbox.

Unfortunately, for every good use of this trick, there seem to be two poor ones. Oh well. Most of the things in TFA are more generally applicable.

Re: Python Idioms [pdf]

#110

Srsly, what Python programmer writes the code in the "Bad" examples therein? This list looks like it's from 2005 or something.

Lists like this aren't for experienced pythonistas, but more for new people to know what things to avoid, and what not to copy if they do come across it online (in an article from 2005...) :-)
Post reply on HN