reflection

Can you use a string to instantiate a class?

Can you use a string to instantiate a class? Question: I’m using a Builder pattern in Python to separate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named ID… (e.g. ID12345). These all inherit from the base Builder class. In my script, I need to instantiate an instance …

Total answers: 6

How to dynamically load a Python class

How to dynamically load a Python class Question: Given a string of a Python class, e.g. my_package.my_module.MyClass, what is the best possible way to load it? In other words I am looking for a equivalent Class.forName() in Java, function in Python. It needs to work on Google App Engine. Preferably this would be a function …

Total answers: 13

How to check whether a variable is a class or not?

How to check whether a variable is a class or not? Question: I was wondering how to check whether a variable is a class (not an instance!) or not. I’ve tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don’t know what type a class would have. For example, in the following …

Total answers: 13

Python decorator makes function forget that it belongs to a class

Python decorator makes function forget that it belongs to a class Question: I am trying to write a decorator to do logging: def logger(myFunc): def new(*args, **keyargs): print ‘Entering %s.%s’ % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() I would like this to print: Entering C.f but instead …

Total answers: 9

How to list all functions in a module?

How to list all functions in a module? Question: I have a Python module installed on my system and I’d like to be able to see what functions/classes/methods are available in it. I want to call the help function on each one. In Ruby I can do something like ClassName.methods to get a list of …

Total answers: 20

Python super class reflection

Python super class reflection Question: If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it’s super classed (A and B)? Something like pseudocode: >>> magicGetSuperClasses(C) (<type ‘A’>, <type ‘B’>) One solution seems to be inspect module and …

Total answers: 4

Calling a function of a module by using its name (a string)

Calling a function of a module by using its name (a string) Question: How do I call a function, using a string with the function’s name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar() Asked By: ricree || Source Answers: Given a module foo with method bar: import foo bar = …

Total answers: 18