Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

111–120 of 174 posts

Re: Python idioms I wish I'd learned earlier

#111

Wow - that's really, really great list. In particular, #7 is something that I didn't even know existed, and I've been hacking around for 2+ years. Instead of: mdict={'gordon':10,'tim':20} >>> print mdict.get('gordon',0) 10 >>> print mdict.get('tim',0) 20 >>> print mdict.get('george',0) 0 I've always done the much more verbose: class defaultdict(dict): def __init__(self, default=None): dict.__init__(self) self.default…

Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing.

whereas dic.get with default value keep returning you the default value without touching your dict.

Re: Python idioms I wish I'd learned earlier

#112
post #104

I came across this when I was first learning Python and it has always impressed me: from random import shuffle deck = ['%s of %s' % (number, suit) for number in '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ') for suit in 'Hearts Clubs Diamonds Spades'.split(' ')] shuffle(deck)

I never liked how people in Python use stringWithSpaces.split instead of a list. Just feels wrong somehow. But I've seen it many times so it's probably pythonic

It makes sense when all the values in the list are text.

Avoids lots of ", "

Re: Python idioms I wish I'd learned earlier

#113
post #90
post #87

Earlier quoted context omitted.

Whhats wrong with 7.?

The default value (the second argument of the `get` method) defaults to `None` anyways. Therefore, D.get(key, None) is just syntax noise (in the best case - in the worst case, it signifies someone who doesn't know/understand Python). D.get(key) should be used instead, or D.get(key, "whatever") if required.

Of course, sometimes I still type:

  D.get(key, None)
since I forget that dict.get and getattr() have different behavior in the case of missing keys/attributes...

Re: Python idioms I wish I'd learned earlier

#114
post #104

I came across this when I was first learning Python and it has always impressed me: from random import shuffle deck = ['%s of %s' % (number, suit) for number in '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ') for suit in 'Hearts Clubs Diamonds Spades'.split(' ')] shuffle(deck)

I never liked how people in Python use stringWithSpaces.split instead of a list. Just feels wrong somehow. But I've seen it many times so it's probably pythonic

I do it entirely, exclusively, only, purely because it requires less punctuation typing. It returns a list anyway. The performance hit is virtually unnoticeable in almost every use case (unless this is a function taking in input strings formatted this way many times per second, but in that case you've got way worse to worry about first...).

Re: Python idioms I wish I'd learned earlier

#115
post #61

"Because I was so used to statically typed languages (where this idiom would be ambiguous), it never occurred to me to put two operators in the same expression. In many languages, 4 > 3 > 2 would return as False, because (4 > 3) would be evaluated as a boolean, and then True > 2 would be evaluated as False." The second half of this is correct, but it has nothing to do with whether the language is statically or dynami…

It's not just a tweak to the parser, and it does have to do with the type system, but you're right that it's not about static typing. The issue is that there are languages (like C) where typing is static but weak, so e.g. booleans are also integers and can have integer operations like '>' applied to them. In other words, the problem is that in C True == 1 and 1 > 2 is a valid expression. In Python, which has strong(e…

Booleans are integers in Python too:

>>> True + 0

1

Re: Python idioms I wish I'd learned earlier

#116
post #86

Sincerely, Transforming Code into Beautiful, Idiomatic Python – by Raymond Hettinger... http://youtu.be/OSGv2VnC0go

I was lucky to watch this video while first learning the language. Every beginner (coming from another language) should watch this to understand the idioms of Python.

Re: Python idioms I wish I'd learned earlier

#118
post #111

Wow - that's really, really great list. In particular, #7 is something that I didn't even know existed, and I've been hacking around for 2+ years. Instead of: mdict={'gordon':10,'tim':20} >>> print mdict.get('gordon',0) 10 >>> print mdict.get('tim',0) 20 >>> print mdict.get('george',0) 0 I've always done the much more verbose: class defaultdict(dict): def __init__(self, default=None): dict.__init__(self) self.default…

Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing. whereas dic.get with default value keep returning you the default value without touching your dict.

re: "Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing."

europa - The dictionary is only modified if you are using a method to modify it. When you are just passively querying it, it's not impacted.

   class defaultdict(dict):

      def __init__(self, default=None):
          dict.__init__(self)
          self.default = default

      def __getitem__(self, key):
          try:
              return dict.__getitem__(self, key)
          except KeyError:
              return self.default

   mdict=defaultdict(0)
   mdict['gordon']=10
   mdict['tim']=20
   print mdict['gordon']   
   print mdict['tim']
   print mdict['george']
   print mdict

   10
   20
   0
   {'tim': 20, 'gordon': 10}

Re: Python idioms I wish I'd learned earlier

#119
post #61

Earlier quoted context omitted.

It's not just a tweak to the parser, and it does have to do with the type system, but you're right that it's not about static typing. The issue is that there are languages (like C) where typing is static but weak, so e.g. booleans are also integers and can have integer operations like '>' applied to them. In other words, the problem is that in C True == 1 and 1 > 2 is a valid expression. In Python, which has strong(e…

Booleans are integers in Python too: >>> True + 0 1

It would be more correct to say that the "bool" type implements an "__int__" method for conversion to an integer, but the types are actually distinct:

    >>> type(True)
    
    >>> type(1)
    
Edit: oops, I'm wrong. "bool" also inherits from "int":

http://stackoverflow.com/questions/8169001/why-is-bool-a-sub...

Re: Python idioms I wish I'd learned earlier

#120

I wish there was an interval set in Python's builtins. I also wish that ranges were an actual proper set implementation - so you could, for example, take intersection and union of ranges. And I wish that Python had an explicit concatenation operator.

You mean like the built in `set` object? https://docs.python.org/2/library/stdtypes.html#set
Post reply on HN