Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Mon Jul 11 19:18:50 EDT 2005


--- Rob Williscroft <rtw at freenet.co.uk> wrote:
> def init_self( init ):
>   class KeywordArgumentError(Exception):
>     pass
>     
>   vn = init.func_code.co_varnames[ 1 : init.func_code.co_argcount ]
>   
>   def decorated_init(self, *args, **kw):
>     off = 0
>     for name in vn:
>       if not name.startswith('_'):
>           if name in kw:
>               value = kw[name]
>           else:
>               value = args[off]
>               off += 1
>               
>           setattr( self, name, value )
>       else:
>         off += 1 #was missing (a bug) in last version.
>         if name in kw:
>           raise KeywordArgumentError(
>               "Use %s not %s" % (name[1:],name) 
>             )
>         if name[1:] in kw:
>           kw[name] = kw[name[1:]]
>           del kw[name[1:]]
>         
>     init( self, *args, **kw )
>   return decorated_init
>               
> 
> class MyClass(object):
>   @init_self
>   def __init__( self, x, _y, z ):
>     print "in __init__() _y =", _y
> 
>   def show( self ):
>     for i in self.__dict__:
>       print 'self.%s = %d' %(i,eval('self.%s' % (i,)))
> 
> MyClass( 1, 2, 3 ).show()
> 
> MyClass( z = 1, x = 2, y = 3 ).show()
> 
> MyClass( z = 1, x = 2, _y = 3 ).show()

Wow!

Here is the output, so everyone can see it immediately:

in __init__() _y = 2
self.x = 1
self.z = 3
in __init__() _y = 3
self.x = 2
self.z = 1
Traceback (most recent call last):
  File "/net/cci/rwgk/decorated_init.py", line 45, in ?
    MyClass( z = 1, x = 2, _y = 3 ).show()
  File "/net/cci/rwgk/decorated_init.py", line 21, in decorated_init
    raise KeywordArgumentError(
__main__.KeywordArgumentError: Use y not _y


I am impressed. I'll do some timings to see where we stand...

Cheers,
        Ralf



		
__________________________________ 
Discover Yahoo! 
Use Yahoo! to plan a weekend, have fun online and more. Check it out! 
http://discover.yahoo.com/



More information about the Python-list mailing list