Schrödinger’s variable: the __class__ cell magically appears if you’re checking for its presence?

This is a weird interaction in Python 3’s implementation of no-argument super. An access to super in a method triggers the addition of a hidden __class__ closure variable referring to the class that defines the method. The parser special-cases a load of the name super in a method by also adding __class__ to the method’s … Read more

Is everything greater than None?

None is always less than any datatype in Python 2 (see object.c). In Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a TypeError. From the 3.0 “what’s new” updates: Python 3.0 has simplified the rules for ordering comparisons: The ordering comparison operators (<, <=, >=, >) … Read more

Prevent creating new attributes outside __init__

I wouldn’t use __dict__ directly, but you can add a function to explicitly “freeze” a instance: class FrozenClass(object): __isfrozen = False def __setattr__(self, key, value): if self.__isfrozen and not hasattr(self, key): raise TypeError( “%r is a frozen class” % self ) object.__setattr__(self, key, value) def _freeze(self): self.__isfrozen = True class Test(FrozenClass): def __init__(self): self.x = … Read more

Get fully qualified class name of an object in Python

With the following program #!/usr/bin/env python import foo def fullname(o): klass = o.__class__ module = klass.__module__ if module == ‘builtins’: return klass.__qualname__ # avoid outputs like ‘builtins.str’ return module + ‘.’ + klass.__qualname__ bar = foo.Bar() print(fullname(bar)) and Bar defined as class Bar(object): def __init__(self, v=42): self.val = v the output is $ ./prog.py foo.Bar … Read more

How to get method parameter names?

Take a look at the inspect module – this will do the inspection of the various code object properties for you. >>> inspect.getfullargspec(a_method) ([‘arg1’, ‘arg2’], None, None, None) The other results are the name of the *args and **kwargs variables, and the defaults provided. ie. >>> def foo(a, b, c=4, *arglist, **keywords): pass >>> inspect.getfullargspec(foo) … Read more