views:

1010

answers:

4
+3  Q: 

Python shortcuts

Python is filled with little neat shortcuts.

For example:

self.data = map(lambda x: list(x), data)

and (although not so pretty)

tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')

among countless others.

In the irc channel, they said "too many to know them all".

I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.

+11  A: 
self.data = map(lambda x: list(x), data)

is dreck -- use

self.data = map(list, data)

if you're a map fanatic (list comprehensions are generally preferred these days). More generally, lambda x: somecallable(x) can always be productively changed to just somecallable, in every context, with nothing but good effect.

As for shortcuts in general, my wife and I did our best to list the most important and useful one in the early part of the Python Cookbook's second edition -- could be a start.

Alex Martelli
Amazing. Thank you. This is the beauty of refactoring in python. Just when i thought i had refactored it to as simple and short as possible, i was wrong. :) Thanks again
lyrae
@lyrae, you're most welcome!-)
Alex Martelli
+3  A: 

Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second:

tuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema'))

Obviously the in operator becomes more advantageous the more values you're testing for.

I would also like to stress that shortening and refactoring is good only to the extent that it improves clarity and readability. (Unless you are code-golfing. ;)

John Y
Ah thanks for this. Feel free to contribute to this thread if you know other neat shortcuts =]
lyrae
+3  A: 

I'm not sure if this is a shortcut, but I love it:

>>> class Enum(object):
        def __init__(self, *keys):
            self.keys = keys
            self.__dict__.update(zip(keys, range(len(keys))))
        def value(self, key):
            return self.keys.index(key)          

>>> colors = Enum("Red", "Blue", "Green", "Yellow", "Purple")
>>> colors.keys
('Red', 'Blue', 'Green', 'Yellow', 'Purple')
>>> colors.Green
2

(I don't know who came up with this, but it wasn't me.)

Robert Rossney
and why would you need it? doesn't list solve it the same way?
SilentGhost
This lets you use enumerated constants in a language that doesn't formally support them. There's a pretty wide range of use cases for those.
Robert Rossney
+1  A: 

I always liked the "unzip" idiom:

>>> zipped = [('a', 1), ('b', 2), ('c', 3)]
>>> zip(*zipped)
[('a', 'b', 'c'), (1, 2, 3)]
>>> 
>>> l,n = zip(*zipped)
>>> l
('a', 'b', 'c')
>>> n
(1, 2, 3)
DopplerShift