Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Is this good Python? PyCon WEB 2017 Lightning Talk

55 views

Published on

Lightning talk I held at https://pyconweb.com/ about how my Python idioms changed over the years, and how trying to write smart (but unreadable) code is bad :)

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Is this good Python? PyCon WEB 2017 Lightning Talk

  1. 1. Is this good Python? No seriously, what do you think? Steffen from TrustYou @tyengineering Lightning talk @ PyCon WEB Munich 2017
  2. 2. Just find me one element in a list def is_what_i_want(el): # something filter(is_what_i_want, els)[0]
  3. 3. Well, if there actually is one try: el = filter(is_what_i_want, els)[0] except IndexError: el = None
  4. 4. Use next(), dream of find_first() - JS and Java 8 have them … el = next((el for el in els if is_what_i_want(el)), None)
  5. 5. Renaming a dictionary key (because Mongo) data["new_name"] = data["old_name"] del data["old_name"]
  6. 6. What do you think, readable? data["new_name"] = data.pop("old_name")
  7. 7. I zip() corpus = list(izip_longest(*[corpus] * batch))
  8. 8. “Defensive programming” - gotta be sure … name = None if user is None else user["name"] # meh … name = (user or {}).get("name") # getting hard to read …
  9. 9. Short-circuiting user = None name = user and user["name"] # What's in "name"? user = () # How about now?
  10. 10. (Or just use JSON schema) http://json-schema.org/
  11. 11. Collections.defaultdict + recursion to the rescue def tree(): return defaultdict(tree) data["props"]["prop"] = # stuff …
  12. 12. Whoops data["porps"] # oops, now "porps" exists
  13. 13. Metaclasses ● Customize class creation ● Customize object creation (__init__ initializes, doesn’t create) ● Confuse readers some_task = VacuumTable(table_name="users") another_task = VacuumTable(table_name="users") assert some_task is another_task

×