Remote Objects - PY

Saturday, April 3, 2010

Google Wave

Friday, March 26, 2010

Dynamic method invocation in python

In this article will see how to invoke a method with arguments

Code :

#sample class
class demo:
#method need to be invoked dynamically
def mymethod(self,myarg):
print(myarg)

#method to invoke a method in object
def invoke_method(method_name,args,obj):
kwargs =args
#get the method from the instance
method=getattr(obj,method_name)
return method(**kwargs)

#argument & value object
arg ={"myarg" : "hello world"}
invoke_method('mymethod',arg,demo())

How it works
  1. Created a sample class demo with a method mymethod
  2. new method invoke_method takes three method name , arguments (name value pairs),instance of the object
  3. Method object is fetched for the instance using getattr() function
  4. Method was invoked with keyworded arguments (**kwargs) - more on kwargs

Labels: ,

Dynamic class loading in python

Code
:


def create(class_name):
#check for module name
module_name,class_name = class_name.rsplit(".",1)
#check if the module already loaded
if module_name not in sys.modules:
#import module
__import__(module_name)
module = sys.modules[module_name]
# fetch class
cls =getattr(module,class_name)
#create an instance of the class
return cls()

#returns an instance of html.parser.HTMLParse
obj = create('html.parser.HTMLParser')

How it works
  1. Get class and module name.'HMTLParser' is the class and 'html.parser' is the module.
  2. Check if the module already loaded.'sys.module' object contains all loaded module list.
  3. If no module exist manually load the module using __import__() function.
  4. Get the module object from the 'sys.modules' using getattr() function.
  5. Get class object form the module object again using getattr() function
  6. Create instance for the object.


Labels: , , ,