Proxying every function in a module

Josh West josh at laculine.com
Fri May 25 14:00:46 EDT 2007


>
> First off, don't attempt to start a new thread by replying to a previous 
> one. Many newsreaders will merge the two, confusing the hell out of 
> everyone and generally not helping.
>   

Ahh, yes. I see what you mean. Explains why it didn't appear the first 
time I posted (until later..).

Sorry for bother and thanks for the advice.
> Second, what makes you think you need a module? I'd have thought an 
> instance of some user-defined class would have been better, as that way 
> you can redefine the __getattr__() method to return appropriate functions.
>   
The functions are ported from a java class static methods. I was trying 
to be "pythonic" - since my 100 functions don't share state, I thought 
they should be packaged as a module rather than as a class of bunch of 
effectively static methods.
> This seems to work, though I haven't tested it extensively (i.e. I have 
> called one instance precisely  once ;-)
>
>  >>> import re
>  >>> pat = re.compile("([a-z]+)(.+)")
>  >>> class myRewriter:
> ...   def srt(self, s):
> ...     m = pat.match(s)
> ...     if not m: raise ValueError(s)
> ...     return m.group(1), m.group(2).lower()
> ...   def __getattr__(self, name):
> ...     n1, n2 = name.split("_")
> ...     def f(val):
> ...       s1, s2 = self.srt(val)
> ...       return "/%s/%s/?sort=%s_%s" % \
> ...               (n1, n2, s1, s2)
> ...     return f
> ...
>  >>> r = myRewriter()
>  >>> r.organisations_list('dateCreated')
> '/organisations/list/?sort=date_created'
>  >>>
>
> regards
>   Steve
>   
Genius! Embarrassingly, I hadn't realised that __getattr__() is called 
when a method is invoked, thus making the method name (attribute name) 
so easily available as a string. I was therefore thinking in terms of 
gnarly introspection/reflection things. This is much better.

Thanks very much





More information about the Python-list mailing list