Skip to main content

Python decorator for automatic initialization instance attributes

Project description


Python decorator for automatic initialization instance attributes


from autoinit import autoinit

class X:
    def __init__(self, a, b, c, d:int, e=99.99, f='some_default_value'):
	    print("__init__ do some another things")

x = X(42, 100, 500, None)
#  Output: "__init__ do some another things"

# Output: {'a': 42, 'b': 100, 'c': 500, 'd': None, 'e': 99.99, 'f': 'some_default_value'}


$ pip install autoinit


Tested in:

  • CPython: 2.7, 3.5-3.8
  • Pypy: 2.7, 3.5, 3.6
  • Jython: 2.7

...but with a high probability will work with other implementations as well.


A lot of elementary assignments inside __init__ are a fairly frequent and rather dull case.

class FiveDimensionRecord:
    def __init__(self, x:int, y:int, z:int, u:int,
                 v:int, dt:typing.Optional[datetime]=None, description:str=''):
        self.x = x
        self.y = y
        self.z = z
        self.u = u
        self.v = v
        self.dt = dt or
        self.description = description

Dataclasses do not make it much more fun, mainly because you still cannot declare attributes in one line

class FiveDimensionRecord:
    x: int
    y: int
    z: int
    u: int
    v: int
    dt: 'typing.Any' = None
    description: str = ''

    def __post_init__(self):
        self.dt = self.dt or

With autoinit it looks much more compact and minimalistic

class FiveDimensionRecord:
    def __init__(self, x:int, y:int, z:int,
                 u:int, v:int, dt=None, description:str=''):
        self.dt = self.dt or


  • @autoinit(exclude='attr') or @autoinit(exclude=['attr1', 'attr2]'): skip specified attributes

  • @autoinit(no_warn=True): do not throw warning if decorator applied to non-__init__ method

  • @autoinit(reverse=True): invert the order of actions - first call the wrapped method (which is usually __init__), and then do assignment

The decorator itself can be equally applied to both the __init__ method and the entire class.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for autoinit, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size autoinit-1.0.0-py2.py3-none-any.whl (4.2 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size autoinit-1.0.0.tar.gz (4.5 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page