xmlrpclib and methods declared at runtime

Brett g Porter bgporter at acm.org
Wed Jul 26 09:08:55 EDT 2006


squid wrote:
> 
> Based on having read the python tutorial and remembering the list of
> built-in functions, my guess would have been calling setattr in the
> constructor or after doing a listMethods operation against the XML-RPC
> server.. That is, assuming the XML-RPC service supports this api..
> something like that.. But that does not seem to be the case here, as a
> search of xmlrpclib.py does not show ANY instances of setattr being
> used. I did, however, notice some cases of classes implementing a
> __getattr__ method, which leads me to the question of how the
> interpreter performs lookup of methods when they are called. Does it
> use getattr itself? Is it possible to, say, effectively override
> getattr for a specific class, thereby returning a pointer to a generic
> function that could be used to handle... well.. everything?
> 

You seem to have gotten it. When Python can't find an attribute in an 
object's dict, it then looks for the magic __getattr__ method. If it's 
present, it passes that method the name that you're looking for. This 
lets you synthesize attributes and methods at runtime.

 >>> class Foo(object):
...    def __getattr__(self, name):
...       return name.upper()
...
 >>> f = Foo()
 >>> f.test
'TEST'

With xml-rpc, a method call on your side of the connection is 
implemented by building up an XML message and sending it to the server 
-- rather than statically try to figure out what oprations the server 
supports, xmlrpclib will happily attempt to call any method name that 
you can think of, and let the server tell you if there's an error.



It's probably not a good idea to let __getattr__ handle EVERYTHING your 
class needs to do, but in cases like this where you don't know in 
advance what the class will need to handle, it lets your code hide the 
magic in a way that lets the users of your code forget that there's 
anything magic going on at all. It just looks like code.

-- 
// Brett g Porter * bgp at bgporter.net
// http://www.bgporter.net/blog



More information about the Python-list mailing list