[Python-ideas] Simple class initialization
Ethan Furman
ethan at stoneleaf.us
Sat Apr 16 18:25:55 CEST 2011
dag.odenhall at gmail.com wrote:
> On 16 April 2011 13:50, Adam Matan <adam at matan.name> wrote:
>> 0. Abstract
>> ===========
>> A class initialization often begins with a long list of explicit variable
>> declaration statements at the __init__() method. This repetitively copies
>> arguments into local data attributes.
>> This article suggests some semi-automatic techniques to shorten and clarify
>> this code section. Comments and responses are highly appreciated.
[snippers]
> class Process:
>
> # Defaults and documentation as class attributes
> pid = None
>
> def __init__(self, **kwargs):
> for k, v in kwargs.iteritems():
> setattr(self, k, v)
I like the initialiser function myself:
8<-------------------------------------------------------------
def acquire(obj, kwargs):
Missing = object()
for kw, val in kwargs.items():
name = '_'+kw
attr = getattr(obj, name, Missing)
if attr is Missing:
name = kw
attr = getattr(obj, name, Missing)
if attr is not Missing:
setattr(obj, name, val)
class Process:
pid = None
ppid = None
cmd = None
reachable = None
user = None
_fd = None
def __init__(self, pid, ppid, cmd, fd, reachable, user):
acquire(self, locals())
print(self.pid)
print(self.ppid)
print(self.cmd)
print(self.reachable)
print(self.user)
print(self._fd)
if __name__ == '__main__':
p = Process(9, 101, 'cd /', 0, 'yes', 'root')
8<-------------------------------------------------------------
Don't think it needs to be in the stdlib, though.
~Ethan~
More information about the Python-ideas
mailing list