User:Robert Ullmann/Python magic

Some useful bits of Python, pure magic.

Unidentified class
You find yourself trying to pass around tuples of several things, or small dicts, and getting confused with dicts of dicts or which index in the tuple, or whatever. The standard answer is to define a class, set up init and del methods, default values for things. Can be done, but we make it easy:

class ufo: def __init__(self, **k): for a in k: setattr(self, a, k[a])

Now you can just instantiate it for whatever use you like:

N.b.: the "F" in the name can be interpreted as any F-word that pleases you.

Static variables
So you want a C-style static variable in your finction? And you discover that Python wants you to define it outside the function, and use a  statement inside. And then when your module gets imported with  there is your variable in the caller's naming scope. Not what you wanted at all, correct?

def static(func, **k): for a in k: func.__dict__.setdefault(a, k[a])

Where you would have written in C:, now it works like this:

def foo: static(foo, x = 0, y = 0)

foo.x += 1 foo.y -= 1

return foo.x, foo.y

What is happening here is that the function definition itself is an object, and you may set and use attributes of it just as with any other object. You can also reference the "static" variables from outside the function if and when you intend to. (That is why we use  on the dict, rather than , see? Also it gets done on every call.) If you don't need an initial default value set within the function, you don't even need  :

def foo: foo.x += 1 return foo.x

foo.x = 0 print foo, foo, foo

Python is cool.