Create hierarchical python object where arguments to methods are from hierarchy
Question: There is an existing module I use containing a class that has methods with
string arguments that take the form:

    
    
    existing_object.existing_method("arg1")
    

or

    
    
    existing_object.existing_method("arg1:arg2")
    

The arguments are in a hierarchical structure. I would like to create a module
that objectifies the arguments and makes them methods of the class of the
imported module such that use would look like this:

    
    
    my_object.arg1.my_method()
    

or

    
    
    my_object.arg1.arg2.my_method()
    

my_method() would call existing_method() while passing it the "arg1:arg2" as
an argument.

If someone could point me in the right direction to get started I'd appreciate
it.


Answer: You can do this with a custom `__getattr__` that returns special method caller
instances:

    
    
    class MethodCaller(object):
        def __init__(self, args, parent):
            self.args = args
            self.parent = parent
        def __getattr__(self, name):
            return MethodCaller(self.args + (name,), self.parent)
        def my_method(self):
            return self.parent.existing_method(':'.join(self.args))
    
    class MyClass(object):
        def __getattr__(self, name):
            return MethodCaller((name,), self)
        def existing_method(self, arg):
            print arg
    

Example:

    
    
    >>> MyClass().arg1.my_method()
    arg1
    >>> MyClass().arg1.arg2.my_method()
    arg1:arg2
    >>> MyClass().foo.bar.my_method()
    foo:bar
    

