Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

April 14, 2013

Python Tricks

if this is a short post, check back some other time.


Python 3

These are more elaborations on, and examples of, Idiomatic Python. They are meant to be self contained. I'll update this post with certain frequency.

enumerate

# enumerator_tester.py
a = [['one', 'two'], ['three', 'four'], ['five', 'size'], ['wen', 'aeto']]
for idx, (i,j) in enumerate(a):
print(i, j, idx)

list comprehensions

floatstrings = ['2.4', '6.4', '7.7', '3.2']
floats = [float(i) for i in floatstrings]
print(floats)
#>>> [2.4, 6.4, 7.7, 3.2]
with an if statement..
floatstrings = ['2.4', '6.4', '7.7', '3.2']
floats = [float(i) for i in floatstrings if float(i) > 6.2]
print(floats)
#>>> [6.4, 7.7]

map

useful for doing something with each member of an iterable, like converting every member into a float. To use the result of map(a, b) as a list you must do list(map(a,b).
floatstrings = ['2.4', '6.4', '7.7', '3.2']
floats = list(map(float, floatstrings))
print(floats)
#>>> [2.4, 6.4, 7.7, 3.2]

operations on and with lists

v1 = 10
v2 = 70
v_rest = [20,30,40,50,60]
v_sandwich = [v1] + v_rest + [v2]
# [10, 20, 30, 40, 50, 60, 70]
view raw demo.py hosted with ❤ by GitHub

Flatten a list

# from twitter SciPy
nested = [[1,2], [3,4]]
flat = [a for b in nested for a in b]

default function argments

use vars() to read the variables available in the local scope.
def default_args(var1=20, var2=50, var3=90):
print(vars())
default_args()
# {'var1': 20, 'var3': 90, 'var2': 50}
argument_object = {'var1': 'override', 'var2': 'also override', 'var3': 'also override this'}
default_args(**argument_object)
# {'var1': 'override', 'var3': 'also override this', 'var2': 'also override'}
view raw demo.py hosted with ❤ by GitHub

checking for Truth

I see quite a bit of verbose if-statements, here's a reminder of what\s possible.
value_list = [True, False, 0, 0.0, 0.1, -1, [], [0], [1]]
for i in value_list:
if i:
print(i, 'is True')
else:
print(i, 'is not True')
'''
True is True
False is not True
0 is not True
0.0 is not True
0.1 is True
-1 is True
[] is not True
[0] is True
[1] is True
'''
view raw truths.py hosted with ❤ by GitHub
and this would print the same list
for i in value_list:
print(i, 'is True' if i else 'is not True')
view raw shorter.py hosted with ❤ by GitHub

any() and all()

if any of the following strings are present in the larger list, return a True
prop_list = ["prop5", "prop4", "prop7", "prop6"]
if any(prop in ("prop1", "prop2", "prop3") for prop in prop_list):
print("yeah")
view raw ruths.py hosted with ❤ by GitHub
or return True only when all items are present.
prop_list = ["prop1", "prop2", "prop3"]
if all(prop in ("prop1", "prop2", "prop3") for prop in prop_list):
print("yeah all")
view raw ruths.py hosted with ❤ by GitHub