Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ron Adam
rrr at ronadam.com
Sun Jul 3 18:07:30 EDT 2005
Bengt Richter wrote:
> What if parameter name syntax were expanded to allow dotted names as binding
> targets in the local scope for the argument or default values? E.g.,
>
> def foometh(self, self.x=0, self.y=0): pass
>
> would have the same effect as
>
> def foometh(self, self.y=0, self.x=0): pass
>
> and there would be a persistent effect in the attributes of self
> (whatever object that was), even with a body of pass.
>
> I'm not sure about foo(self, **{'self.x':0, 'self.y':0}), but if
> you didn't capture the dict with a **kw formal parameter, IWT you'd
> have to be consistent and effect the attribute bindings implied.
>
> (Just a non-thought-out bf here, not too serious ;-)
>
> Regards,
> Bengt Richter
Well it works the other way around to some degree.
def foo(self, x=x, y=y):pass
x=x binds the class variables to the arguments without the self. if no
value is given.
Which is kind of strange, since x by it self gives an error if no value
is given. The strange part is x=x is not the same as just x. I
understand why, but it still looks odd.
Why isn't there a dict method to get a sub dict from a key list?
Fromkeys doesn't quite do it.
sub-dict = dict.subdict(key_list)
Or have dict.copy() take a key list. (?)
<Just a thought.>
The following works and doesn't seem too obscure, although the x=x,
etc.. could be annoying if they were a lot of long names.
Seems like mutable default arguments is what's needed to make it work,
not that it's needed IMO. But it's an interesting problem.
def subdict(dict, keys):
d = {}
for k in keys:
d[k] = dict[k]
return d
class foo(object):
x = 1
y = 2
z = 3
def __init__(self,x=x,y=y,z=z):
save_these = subdict(locals(),['x','y'])
self.__dict__.update(save_these)
# rest of code
print self.x, self.y, self.z
f = foo()
f = foo(5,6,7)
More information about the Python-list
mailing list