Can you list the keyword arguments a function receives?

A little nicer than inspecting the code object directly and working out the variables is to use the inspect module. >>> import inspect >>> def func(a,b,c=42, *args, **kwargs): pass >>> inspect.getargspec(func) ([‘a’, ‘b’, ‘c’], ‘args’, ‘kwargs’, (42,)) If you want to know if its callable with a particular set of args, you need the args … Read more

List all base classes in a hierarchy of given class?

inspect.getmro(cls) works for both new and old style classes and returns the same as NewClass.mro(): a list of the class and all its ancestor classes, in the order used for method resolution. >>> class A(object): >>> pass >>> >>> class B(A): >>> pass >>> >>> import inspect >>> inspect.getmro(B) (<class ‘__main__.B’>, <class ‘__main__.A’>, <type ‘object’>)

Ruby: kind_of? vs. instance_of? vs. is_a?

kind_of? and is_a? are synonymous. instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass. Example: “hello”.is_a? Object and “hello”.kind_of? Object return true because “hello” is a String and String is a subclass of Object. However “hello”.instance_of? Object returns … Read more

Get __name__ of calling function’s module in Python

Check out the inspect module: inspect.stack() will return the stack information. Inside a function, inspect.stack()[1] will return your caller’s stack. From there, you can get more information about the caller’s function name, module, etc. See the docs for details: http://docs.python.org/library/inspect.html Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series: … Read more