python-attrs

How to specify that an attribute must be a list of (say) integers, not just a list?

梦想的初衷 提交于 2019-12-01 02:07:45
问题 Using the attrs libary and Python 3.6, I thought the following would allow me to specify that x and y can only contain integers: import attr @attr.s class C: x : List[int] = attr.ib() # not working y = attr.ib(type=List[int]) # not working either Both of the commented lines throw a NameError: name 'List' is not defined . The reasons I expected that to work are these: (1) The types section of the attr documentation includes the following passage: " attrs also allows you to associate a type

How do I avoid the “self.x = x; self.y = y; self.z = z” pattern in __init__?

痞子三分冷 提交于 2019-11-28 15:15:26
I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should the class inherit from namedtuple instead? Edit: If you have python 3.7+ just use dataclasses A decorator solution that keeps the signature: import decorator import inspect import sys @decorator.decorator def simple_init(func, self, *args, **kws): """ @simple_init def __init__(self,a,b,...,z) dosomething() behaves like def __init__(self,a,b,...,z) self.a = a self.b = b ... self.z =