Skip to content

Instantly share code, notes, and snippets.

@pedramamini
Last active September 30, 2015 17:18
Show Gist options
  • Save pedramamini/1833834 to your computer and use it in GitHub Desktop.
Save pedramamini/1833834 to your computer and use it in GitHub Desktop.
Python: Ruby style metthodmissing hack
class proxy:
"""
Hack to get Ruby methodmissing functionality.
"""
####################################################################################################################
def __getattr__ (self, method_name):
'''
This routine is called by default when a requested attribute (or method) is accessed that has no definition.
Unfortunately __getattr__ only passes the requested method name and not the arguments. So we extend the
functionality with a little lambda magic to the routine method_missing(). Which is actually how Ruby handles
missing methods by default ... with arguments. Now we are just as cool as Ruby.
@type method_name: String
@param method_name: The name of the requested and undefined attribute (or method in our case).
@rtype: Lambda
@return: Lambda magic passing control (and in turn the arguments we want) to self.method_missing().
'''
return lambda *args, **kwargs: self.method_missing(method_name, *args, **kwargs)
####################################################################################################################
def method_missing (self, method_name, *args, **kwargs):
'''
See the notes for __getattr__ for related notes. This method is called, in the Ruby fashion, with the method
name and arguments for any requested but undefined class method.
@type method_name: String
@param method_name: The name of the requested and undefined attribute (or method in our case).
@rtype: Mixed
@return: Return value of the mirrored method.
'''
exec("method_pointer = self.%s" % method_name)
return method_pointer(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment