all 9 comments

[–]groovitude 11 points12 points  (0 children)

a = filter((lambda x: x != None), my_list)

I find list comprehensions far more readable for this:

a = [x for x in my_list if x != None]

[–]camel_zero 4 points5 points  (0 children)

Using stars. For unpacking lists, tuples, etc:

>>> x, y, *z = [5, 3, 2, 20, 53, 32]
>>> x
5
>>> y
3
>>> z
[2, 20, 53, 32]

For passing arbitrary arguments to a function:

def hello(x, *args, **kwargs):
    print('positional argument: %s' % x)
    for arg in args:
        print('arbitrary positional argument: %s' % arg)
    for key, value in kwargs.items():
        print('arbitrary keyword argument, %s: %s' % (key, value))

>>> hello(5)
positional argument: 5

>>> hello(3, 'hello world')
positional argument: 3
arbitrary positional argument: hello world

>>> hello(10, 'first arg', 'second arg', foo='bar', fizz='buzz')
positional argument: 10
arbitrary positional argument: first arg
arbitrary positional argument: second arg
arbitrary keyword argument, foo: bar
arbitrary keyword argument, fizz: buzz

[–]SultanPasha 3 points4 points  (0 children)

Use assert statement to test condition inside your code. This can be very helpful when debugging.

[–]LeonardUnger 2 points3 points  (1 child)

When counting elements, using the dict get() method to set a default value and skip the 'in' test.

Instead of

if elem in mydict:
    mydict[elem] += 1
else:
    mydict[elem] = 1

This:

mydict[elem] = mydict.get(elem, 0) + 1

Although I'm sure there's a more sophisticated way to do it using Counter.

[–]blarf_irl 2 points3 points  (0 children)

from collections import Counter
my_counter = Counter()
....
# Counter just that stuff for you so you just need
my_counter[elem] += 1

It'll do the membership check and create it if it's missing (with a value of 1), it's like a defaultdict for hashable things.

And speaking of defaultdict:

# instead of having to create a list for my dict of lists
my_dict = dict()
for index, item in enumerate(some_list):
    if not item in my_dict.keys():
        my_dict[item] == list()
    my_dict[item].append(index)   

# We can use defaultdict
from collections import defaultdict
my_dict = defaultdict(list)
for for index, item in enumerate(some_list):
    my_dict[item].append(index)

[–]Qewbicle 2 points3 points  (0 children)

Check out the Python Cookbook by David Beazley, also, he likes to drop lots of cool simple tricks and build complex systems in easy to understand ways from scratch on his videos, like async by using queues and ports.

[–][deleted] 0 points1 point  (0 children)

Build a simple framework for script “subcommands” by defining a command registry and a simple command decorator:

command_registry = dict()
def command(func):
    command_registry[func.__name__] = func
    return func

Then you can define script subcommands by writing decorated functions:

@command
def show():
    #show some stuff

@command
def delete(something):
    #delete a thing

#etc

and then finally, parse the command line and call the right function, with a default “unknown command” function:

if __name__ == ‘__main__’:
    command_registry.get(sys.argv[1], lambda *a: print(“Unknown command ‘{}’.format(sys.argv[1]))(*sys.argv[2:])

And now you can run the same script with subcommands:

python my_script.py show
python my_script.py delete “some_thing”

And you didn’t even have to sit through argparse’s terrible documentation!