<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p>

<pre><code>class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3
</code></pre>

[{'answer_id': 35990, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 6, 'selected': False, 'text': "<p>How about a dictionary?</p>\n\n<p>Something like this:</p>\n\n<pre><code>myStruct = {'field1': 'some val', 'field2': 'some val'}\n</code></pre>\n\n<p>Then you can use this to manipulate values:</p>\n\n<pre><code>print myStruct['field1']\nmyStruct['field2'] = 'some other values'\n</code></pre>\n\n<p>And the values don't have to be strings.  They can be pretty much any other object.</p>\n"}, {'answer_id': 35993, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 7, 'selected': False, 'text': '<p>You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).</p>\n\n<p>For everything else you can use dictionary, or a utility class like <a href="http://code.activestate.com/recipes/52308/" rel="noreferrer">this one</a>:</p>\n\n<pre><code>&gt;&gt;&gt; class Bunch:\n...     def __init__(self, **kwds):\n...         self.__dict__.update(kwds)\n...\n&gt;&gt;&gt; mystruct = Bunch(field1=value1, field2=value2)\n</code></pre>\n\n<p>I think the "definitive" discussion is <a href="http://books.google.com/books?id=Q0s6Vgb98CQC&amp;lpg=PT212&amp;dq=Python%20Cookbook%20%22Collecting%20a%20Bunch%20of%20Named%20Items%22&amp;hl=en&amp;pg=PT213#v=onepage&amp;q&amp;f=false" rel="noreferrer">here</a>, in the published version of the Python Cookbook.</p>\n'}, {'answer_id': 36033, 'author': 'gz.', 'author_id': 3665, 'author_profile': 'https://Stackoverflow.com/users/3665', 'pm_score': 9, 'selected': False, 'text': '<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="noreferrer">named tuple</a>, which was added to the <a href="http://docs.python.org/library/collections.html" rel="noreferrer">collections module</a> in the standard library in Python 2.6. It\'s also possible to use Raymond Hettinger\'s <a href="http://code.activestate.com/recipes/500261/" rel="noreferrer">named tuple</a> recipe if you need to support Python 2.4.</p>\n\n<p>It\'s nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:</p>\n\n<pre><code>from collections import namedtuple\nMyStruct = namedtuple("MyStruct", "field1 field2 field3")\n</code></pre>\n\n<p>The newly created type can be used like this:</p>\n\n<pre><code>m = MyStruct("foo", "bar", "baz")\n</code></pre>\n\n<p>You can also use named arguments:</p>\n\n<pre><code>m = MyStruct(field1="foo", field2="bar", field3="baz")\n</code></pre>\n'}, {'answer_id': 36034, 'author': 'Vicent Marti', 'author_id': 4381, 'author_profile': 'https://Stackoverflow.com/users/4381', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>dF: that\'s pretty cool... I didn\'t\n  know that I could access the fields in\n  a class using dict.</p>\n  \n  <p>Mark: the situations that I wish I had\n  this are precisely when I want a tuple\n  but nothing as "heavy" as a\n  dictionary.</p>\n</blockquote>\n\n<p>You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).</p>\n\n<p>...Which leads us to your second comment. Believing that Python dicts are "heavy" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That\'s not good.</p>\n\n<p>You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something.</p>\n'}, {'answer_id': 36061, 'author': 'PabloG', 'author_id': 394, 'author_profile': 'https://Stackoverflow.com/users/394', 'pm_score': 4, 'selected': False, 'text': '<p>You can also pass the init parameters to the instance variables by position</p>\n\n<pre><code># Abstract struct class       \nclass Struct:\n    def __init__ (self, *argv, **argd):\n        if len(argd):\n            # Update by dictionary\n            self.__dict__.update (argd)\n        else:\n            # Update by position\n            attrs = filter (lambda x: x[0:2] != "__", dir(self))\n            for n in range(len(argv)):\n                setattr(self, attrs[n], argv[n])\n\n# Specific class\nclass Point3dStruct (Struct):\n    x = 0\n    y = 0\n    z = 0\n\npt1 = Point3dStruct()\npt1.x = 10\n\nprint pt1.x\nprint "-"*10\n\npt2 = Point3dStruct(5, 6)\n\nprint pt2.x, pt2.y\nprint "-"*10\n\npt3 = Point3dStruct (x=1, y=2, z=3)\nprint pt3.x, pt3.y, pt3.z\nprint "-"*10\n</code></pre>\n'}, {'answer_id': 3761729, 'author': 'Jose M Balaguer', 'author_id': 454110, 'author_profile': 'https://Stackoverflow.com/users/454110', 'pm_score': 6, 'selected': False, 'text': '<p>Perhaps you are looking for Structs without constructors:</p>\n\n<pre><code>class Sample:\n  name = \'\'\n  average = 0.0\n  values = None # list cannot be initialized here!\n\n\ns1 = Sample()\ns1.name = "sample 1"\ns1.values = []\ns1.values.append(1)\ns1.values.append(2)\ns1.values.append(3)\n\ns2 = Sample()\ns2.name = "sample 2"\ns2.values = []\ns2.values.append(4)\n\nfor v in s1.values:   # prints 1,2,3 --&gt; OK.\n  print v\nprint "***"\nfor v in s2.values:   # prints 4 --&gt; OK.\n  print v\n</code></pre>\n'}, {'answer_id': 18792190, 'author': 'Phlip', 'author_id': 193980, 'author_profile': 'https://Stackoverflow.com/users/193980', 'pm_score': 4, 'selected': False, 'text': '<p>Whenever I need an "instant data object that also behaves like a dictionary" (I <em>don\'t</em> think of C structs!), I think of this cute hack:</p>\n\n<pre><code>class Map(dict):\n    def __init__(self, **kwargs):\n        super(Map, self).__init__(**kwargs)\n        self.__dict__ = self\n</code></pre>\n\n<p>Now you can just say:</p>\n\n<pre><code>struct = Map(field1=\'foo\', field2=\'bar\', field3=42)\n\nself.assertEquals(\'bar\', struct.field2)\nself.assertEquals(42, struct[\'field3\'])\n</code></pre>\n\n<p>Perfectly handy for those times when you need a "data bag that\'s NOT a class", and for when namedtuples are incomprehensible...</p>\n'}, {'answer_id': 26826089, 'author': 'Sujal Sheth', 'author_id': 2042079, 'author_profile': 'https://Stackoverflow.com/users/2042079', 'pm_score': 3, 'selected': False, 'text': '<p>You access C-Style struct in python in following way.</p>\n\n<pre><code>class cstruct:\n    var_i = 0\n    var_f = 0.0\n    var_str = ""\n</code></pre>\n\n<h1>if you just want use object of cstruct</h1>\n\n<pre><code>obj = cstruct()\nobj.var_i = 50\nobj.var_f = 50.00\nobj.var_str = "fifty"\nprint "cstruct: obj i=%d f=%f s=%s" %(obj.var_i, obj.var_f, obj.var_str)\n</code></pre>\n\n<h1>if you want to create an array of objects of cstruct</h1>\n\n<pre><code>obj_array = [cstruct() for i in range(10)]\nobj_array[0].var_i = 10\nobj_array[0].var_f = 10.00\nobj_array[0].var_str = "ten"\n\n#go ahead and fill rest of array instaces of struct\n\n#print all the value\nfor i in range(10):\n    print "cstruct: obj_array i=%d f=%f s=%s" %(obj_array[i].var_i, obj_array[i].var_f, obj_array[i].var_str)\n</code></pre>\n\n<p>Note:\ninstead of \'cstruct\' name, please use your struct name\ninstead of var_i, var_f, var_str, please define your structure\'s member variable. </p>\n'}, {'answer_id': 29212925, 'author': 'user124757', 'author_id': 4094380, 'author_profile': 'https://Stackoverflow.com/users/4094380', 'pm_score': 3, 'selected': False, 'text': '<p>This might be a bit late but I made a solution using Python Meta-Classes (decorator version below too).</p>\n\n<p>When <code>__init__</code> is called during run time, it grabs each of the arguments and their value and assigns them as instance variables to your class. This way you can make a struct-like class without having to assign every value manually.</p>\n\n<p>My example has no error checking so it is easier to follow.</p>\n\n<pre><code>class MyStruct(type):\n    def __call__(cls, *args, **kwargs):\n        names = cls.__init__.func_code.co_varnames[1:]\n\n        self = type.__call__(cls, *args, **kwargs)\n\n        for name, value in zip(names, args):\n            setattr(self , name, value)\n\n        for name, value in kwargs.iteritems():\n            setattr(self , name, value)\n        return self \n</code></pre>\n\n<p>Here it is in action.</p>\n\n<pre><code>&gt;&gt;&gt; class MyClass(object):\n    __metaclass__ = MyStruct\n    def __init__(self, a, b, c):\n        pass\n\n\n&gt;&gt;&gt; my_instance = MyClass(1, 2, 3)\n&gt;&gt;&gt; my_instance.a\n1\n&gt;&gt;&gt; \n</code></pre>\n\n<p>I <a href="http://www.reddit.com/r/Python/comments/300psq/i_made_a_cstyle_struct_using_a_metaclass_to_save/" rel="noreferrer">posted it on reddit</a> and <a href="http://www.reddit.com/user/matchu" rel="noreferrer">/u/matchu</a> posted a decorator version which is cleaner. I\'d encourage you to use it unless you want to expand the metaclass version.</p>\n\n<pre><code>&gt;&gt;&gt; def init_all_args(fn):\n    @wraps(fn)\n    def wrapped_init(self, *args, **kwargs):\n        names = fn.func_code.co_varnames[1:]\n\n        for name, value in zip(names, args):\n            setattr(self, name, value)\n\n        for name, value in kwargs.iteritems():\n            setattr(self, name, value)\n\n    return wrapped_init\n\n&gt;&gt;&gt; class Test(object):\n    @init_all_args\n    def __init__(self, a, b):\n        pass\n\n\n&gt;&gt;&gt; a = Test(1, 2)\n&gt;&gt;&gt; a.a\n1\n&gt;&gt;&gt; \n</code></pre>\n'}, {'answer_id': 31062667, 'author': 'Ella Rose', 'author_id': 3103584, 'author_profile': 'https://Stackoverflow.com/users/3103584', 'pm_score': 5, 'selected': False, 'text': '<p>You can subclass the C structure that is available in the standard library. The <a href="https://docs.python.org/2/library/ctypes.html">ctypes</a> module provides a <a href="https://docs.python.org/2/library/ctypes.html#structures-and-unions">Structure class</a>. The example from the docs:</p>\n\n<pre><code>&gt;&gt;&gt; from ctypes import *\n&gt;&gt;&gt; class POINT(Structure):\n...     _fields_ = [("x", c_int),\n...                 ("y", c_int)]\n...\n&gt;&gt;&gt; point = POINT(10, 20)\n&gt;&gt;&gt; print point.x, point.y\n10 20\n&gt;&gt;&gt; point = POINT(y=5)\n&gt;&gt;&gt; print point.x, point.y\n0 5\n&gt;&gt;&gt; POINT(1, 2, 3)\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in ?\nValueError: too many initializers\n&gt;&gt;&gt;\n&gt;&gt;&gt; class RECT(Structure):\n...     _fields_ = [("upperleft", POINT),\n...                 ("lowerright", POINT)]\n...\n&gt;&gt;&gt; rc = RECT(point)\n&gt;&gt;&gt; print rc.upperleft.x, rc.upperleft.y\n0 5\n&gt;&gt;&gt; print rc.lowerright.x, rc.lowerright.y\n0 0\n&gt;&gt;&gt;\n</code></pre>\n'}, {'answer_id': 32448434, 'author': 'ArtOfWarfare', 'author_id': 901641, 'author_profile': 'https://Stackoverflow.com/users/901641', 'pm_score': 3, 'selected': False, 'text': "<p>I wrote a decorator which you can use on any method to make it so that all of the arguments passed in, or any defaults, are assigned to the instance.</p>\n\n<pre><code>def argumentsToAttributes(method):\n    argumentNames = method.func_code.co_varnames[1:]\n\n    # Generate a dictionary of default values:\n    defaultsDict = {}\n    defaults = method.func_defaults if method.func_defaults else ()\n    for i, default in enumerate(defaults, start = len(argumentNames) - len(defaults)):\n        defaultsDict[argumentNames[i]] = default\n\n    def newMethod(self, *args, **kwargs):\n        # Use the positional arguments.\n        for name, value in zip(argumentNames, args):\n            setattr(self, name, value)\n\n        # Add the key word arguments. If anything is missing, use the default.\n        for name in argumentNames[len(args):]:\n            setattr(self, name, kwargs.get(name, defaultsDict[name]))\n\n        # Run whatever else the method needs to do.\n        method(self, *args, **kwargs)\n\n    return newMethod\n</code></pre>\n\n<p>A quick demonstration. Note that I use a positional argument <code>a</code>, use the default value for <code>b</code>, and a named argument <code>c</code>. I then print all 3 referencing <code>self</code>, to show that they've been properly assigned before the method is entered.</p>\n\n<pre><code>class A(object):\n    @argumentsToAttributes\n    def __init__(self, a, b = 'Invisible', c = 'Hello'):\n        print(self.a)\n        print(self.b)\n        print(self.c)\n\nA('Why', c = 'Nothing')\n</code></pre>\n\n<p>Note that my decorator should work with any method, not just <code>__init__</code>.</p>\n"}, {'answer_id': 40488966, 'author': 'Jason C', 'author_id': 616460, 'author_profile': 'https://Stackoverflow.com/users/616460', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t see this answer here, so I figure I\'ll add it since I\'m leaning Python right now and just discovered it. The <a href="https://docs.python.org/2/tutorial/classes.html" rel="noreferrer">Python tutorial</a> (Python 2 in this case) gives the following simple and effective example:</p>\n\n<pre><code>class Employee:\n    pass\n\njohn = Employee()  # Create an empty employee record\n\n# Fill the fields of the record\njohn.name = \'John Doe\'\njohn.dept = \'computer lab\'\njohn.salary = 1000\n</code></pre>\n\n<p>That is, an empty class object is created, then instantiated, and the fields are added dynamically.</p>\n\n<p>The up-side to this is its really simple. The downside is it isn\'t particularly self-documenting (the intended members aren\'t listed anywhere in the class "definition"), and unset fields can cause problems when accessed. Those two problems can be solved by:</p>\n\n<pre><code>class Employee:\n    def __init__ (self):\n        self.name = None # or whatever\n        self.dept = None\n        self.salary = None\n</code></pre>\n\n<p>Now at a glance you can at least see what fields the program will be expecting.</p>\n\n<p>Both are prone to typos, <code>john.slarly = 1000</code> will succeed. Still, it works.</p>\n'}, {'answer_id': 44989925, 'author': 'Yujun Li', 'author_id': 7963712, 'author_profile': 'https://Stackoverflow.com/users/7963712', 'pm_score': 0, 'selected': False, 'text': '<p>I think Python structure dictionary is suitable for this requirement.</p>\n\n<pre class="lang-py prettyprint-override"><code>d = dict{}\nd[field1] = field1\nd[field2] = field2\nd[field2] = field3\n</code></pre>\n'}, {'answer_id': 45426493, 'author': 'Rotareti', 'author_id': 1612318, 'author_profile': 'https://Stackoverflow.com/users/1612318', 'pm_score': 9, 'selected': False, 'text': '<h2><em>Update</em>: Data Classes</h2>\n\n<p>With the introduction of <a href="https://docs.python.org/3/library/dataclasses.html" rel="noreferrer"><em>Data Classes</em></a> in <strong>Python 3.7</strong> we get very close. </p>\n\n<p>The following example is similar to the <em>NamedTuple</em> example below, but the resulting object is <strong>mutable</strong> and it allows for default values.</p>\n\n<pre><code>from dataclasses import dataclass\n\n\n@dataclass\nclass Point:\n    x: float\n    y: float\n    z: float = 0.0\n\n\np = Point(1.5, 2.5)\n\nprint(p)  # Point(x=1.5, y=2.5, z=0.0)\n</code></pre>\n\n<p>This plays nicely with the new <a href="https://docs.python.org/3/library/typing.html" rel="noreferrer">typing</a> module in case you want to use more specific type annotations.</p>\n\n<p>I\'ve been waiting desperately for this! If you ask me, <em>Data Classes</em> and the new <em>NamedTuple</em> declaration, combined with the <em>typing</em> module are a godsend!</p>\n\n<h2>Improved NamedTuple declaration</h2>\n\n<p>Since <strong>Python 3.6</strong> it became quite simple and beautiful (IMHO), as long as you can live with <strong>immutability</strong>.</p>\n\n<p>A <a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple" rel="noreferrer">new way of declaring NamedTuples</a> was introduced, which allows for <a href="https://docs.python.org/3/library/typing.html" rel="noreferrer">type annotations</a> as well:</p>\n\n<pre><code>from typing import NamedTuple\n\n\nclass User(NamedTuple):\n    name: str\n\n\nclass MyStruct(NamedTuple):\n    foo: str\n    bar: int\n    baz: list\n    qux: User\n\n\nmy_item = MyStruct(\'foo\', 0, [\'baz\'], User(\'peter\'))\n\nprint(my_item) # MyStruct(foo=\'foo\', bar=0, baz=[\'baz\'], qux=User(name=\'peter\'))\n</code></pre>\n'}, {'answer_id': 45517161, 'author': 'w_jay', 'author_id': 6776633, 'author_profile': 'https://Stackoverflow.com/users/6776633', 'pm_score': 3, 'selected': False, 'text': '<p>Some the answers here are massively elaborate. The simplest option I\'ve found is (from: <a href="http://norvig.com/python-iaq.html" rel="noreferrer">http://norvig.com/python-iaq.html</a>):</p>\n\n<pre><code>class Struct:\n    "A structure that can have any fields defined."\n    def __init__(self, **entries): self.__dict__.update(entries)\n</code></pre>\n\n<p>Initialising:</p>\n\n<pre><code>&gt;&gt;&gt; options = Struct(answer=42, linelen=80, font=\'courier\')\n&gt;&gt;&gt; options.answer\n42\n</code></pre>\n\n<p>adding more:</p>\n\n<pre><code>&gt;&gt;&gt; options.cat = "dog"\n&gt;&gt;&gt; options.cat\ndog\n</code></pre>\n\n<p><strong>edit:</strong> Sorry didn\'t see this example already further down.</p>\n'}, {'answer_id': 47016739, 'author': 'Galaxy', 'author_id': 159695, 'author_profile': 'https://Stackoverflow.com/users/159695', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/32448434/159695">https://stackoverflow.com/a/32448434/159695</a> does not work in Python3.</p>\n\n<p><a href="https://stackoverflow.com/a/35993/159695">https://stackoverflow.com/a/35993/159695</a> works in Python3.</p>\n\n<p>And I extends it to add default values.</p>\n\n<pre><code>class myStruct:\n    def __init__(self, **kwds):\n        self.x=0\n        self.__dict__.update(kwds) # Must be last to accept assigned member variable.\n    def __repr__(self):\n        args = [\'%s=%s\' % (k, repr(v)) for (k,v) in vars(self).items()]\n        return \'%s(%s)\' % ( self.__class__.__qualname__, \', \'.join(args) )\n\na=myStruct()\nb=myStruct(x=3,y=\'test\')\nc=myStruct(x=\'str\')\n\n&gt;&gt;&gt; a\nmyStruct(x=0)\n&gt;&gt;&gt; b\nmyStruct(x=3, y=\'test\')\n&gt;&gt;&gt; c\nmyStruct(x=\'str\')\n</code></pre>\n'}, {'answer_id': 47140549, 'author': 'normanius', 'author_id': 3388962, 'author_profile': 'https://Stackoverflow.com/users/3388962', 'pm_score': 2, 'selected': False, 'text': '<p>Personally, I like this variant too. It extends <a href="https://stackoverflow.com/a/35993/3388962">@dF\'s answer</a>.</p>\n\n<pre><code>class struct:\n    def __init__(self, *sequential, **named):\n        fields = dict(zip(sequential, [None]*len(sequential)), **named)\n        self.__dict__.update(fields)\n    def __repr__(self):\n        return str(self.__dict__)\n</code></pre>\n\n<p>It supports two modes of initialization (that can be blended):</p>\n\n<pre><code># Struct with field1, field2, field3 that are initialized to None.\nmystruct1 = struct("field1", "field2", "field3") \n# Struct with field1, field2, field3 that are initialized according to arguments.\nmystruct2 = struct(field1=1, field2=2, field3=3)\n</code></pre>\n\n<p>Also, it prints nicer: </p>\n\n<pre><code>print(mystruct2)\n# Prints: {\'field3\': 3, \'field1\': 1, \'field2\': 2}\n</code></pre>\n'}, {'answer_id': 49560899, 'author': 'PS1', 'author_id': 9570787, 'author_profile': 'https://Stackoverflow.com/users/9570787', 'pm_score': 2, 'selected': False, 'text': '<p>The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it\'s values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn\'t.</p>\n\n<pre><code>_class_template = """\\\nclass {typename}:\ndef __init__(self, *args, **kwargs):\n    fields = {field_names!r}\n\n    for x in fields:\n        setattr(self, x, None)            \n\n    for name, value in zip(fields, args):\n        setattr(self, name, value)\n\n    for name, value in kwargs.items():\n        setattr(self, name, value)            \n\ndef __repr__(self):\n    return str(vars(self))\n\ndef __setattr__(self, name, value):\n    if name not in {field_names!r}:\n        raise KeyError("invalid name: %s" % name)\n    object.__setattr__(self, name, value)            \n"""\n\ndef struct(typename, field_names):\n\n    class_definition = _class_template.format(\n        typename = typename,\n        field_names = field_names)\n\n    namespace = dict(__name__=\'struct_%s\' % typename)\n    exec(class_definition, namespace)\n    result = namespace[typename]\n    result._source = class_definition\n\n    return result\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Person = struct(\'Person\', [\'firstname\',\'lastname\'])\ngeneric = Person()\nmichael = Person(\'Michael\')\njones = Person(lastname = \'Jones\')\n\n\nIn [168]: michael.middlename = \'ben\'\nTraceback (most recent call last):\n\n  File "&lt;ipython-input-168-b31c393c0d67&gt;", line 1, in &lt;module&gt;\nmichael.middlename = \'ben\'\n\n  File "&lt;string&gt;", line 19, in __setattr__\n\nKeyError: \'invalid name: middlename\'\n</code></pre>\n'}, {'answer_id': 49789270, 'author': 'Oamar Kanji', 'author_id': 7055858, 'author_profile': 'https://Stackoverflow.com/users/7055858', 'pm_score': 5, 'selected': False, 'text': '<p>I would also like to add a solution that uses <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="noreferrer">slots</a>:</p>\n\n<pre><code>class Point:\n    __slots__ = ["x", "y"]\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n</code></pre>\n\n<p>Definitely check the documentation for slots but a quick explanation of slots is that it is python\'s way of saying: "If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these <em>slotted</em> attributes".</p>\n\n<p>Example of adding attributes to class instance (thus not using slots):</p>\n\n<pre><code>class Point:\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\np1 = Point(3,5)\np1.z = 8\nprint(p1.z)\n</code></pre>\n\n<p>Output: 8</p>\n\n<p>Example of trying to add attributes to class instance where slots was used:</p>\n\n<pre><code>class Point:\n    __slots__ = ["x", "y"]\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\np1 = Point(3,5)\np1.z = 8\n</code></pre>\n\n<p>Output: AttributeError: \'Point\' object has no attribute \'z\'</p>\n\n<p>This can effectively works as a struct and uses less memory than a class (like a struct would, although I have not researched exactly how much). It is recommended to use slots if you will be creating a large amount of instances of the object and do not need to add attributes. A point object is a good example of this as it is likely that one may instantiate many points to describe a dataset.</p>\n'}, {'answer_id': 53721171, 'author': 'שמואל ביאליסטוקי', 'author_id': 9184115, 'author_profile': 'https://Stackoverflow.com/users/9184115', 'pm_score': 2, 'selected': False, 'text': '<p>There is a python package exactly for this purpose. see <a href="https://github.com/st0ky/cstruct2py/tree/dab23e4e0b6a920c3286c7b44d4e14664d50dc58" rel="nofollow noreferrer">cstruct2py</a></p>\n\n<p><code>cstruct2py</code> is a pure python library for generate python classes from C code and use them to pack and unpack data. The library can parse C headres (structs, unions, enums, and arrays declarations) and emulate them in python. The generated pythonic classes can parse and pack the data.</p>\n\n<p>For example:</p>\n\n<pre><code>typedef struct {\n  int x;\n  int y;\n} Point;\n\nafter generating pythonic class...\np = Point(x=0x1234, y=0x5678)\np.packed == "\\x34\\x12\\x00\\x00\\x78\\x56\\x00\\x00"\n</code></pre>\n\n<blockquote>\n  <p><strong>How to use</strong></p>\n</blockquote>\n\n<p>First we need to generate the pythonic structs:</p>\n\n<pre><code>import cstruct2py\nparser = cstruct2py.c2py.Parser()\nparser.parse_file(\'examples/example.h\')\n</code></pre>\n\n<p>Now we can import all names from the C code:</p>\n\n<pre><code>parser.update_globals(globals())\n</code></pre>\n\n<p>We can also do that directly:</p>\n\n<pre><code>A = parser.parse_string(\'struct A { int x; int y;};\')\n</code></pre>\n\n<p>Using types and defines from the C code</p>\n\n<pre><code>a = A()\na.x = 45\nprint a\nbuf = a.packed\nb = A(buf)\nprint b\nc = A(\'aaaa11112222\', 2)\nprint c\nprint repr(c)\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>{\'x\':0x2d, \'y\':0x0}\n{\'x\':0x2d, \'y\':0x0}\n{\'x\':0x31316161, \'y\':0x32323131}\nA(\'aa111122\', x=0x31316161, y=0x32323131)\n</code></pre>\n\n<blockquote>\n  <p><strong>Clone</strong></p>\n</blockquote>\n\n<p>For clone <code>cstruct2py</code> run:</p>\n\n<pre><code>git clone https://github.com/st0ky/cstruct2py.git --recursive\n</code></pre>\n'}, {'answer_id': 54400995, 'author': 'gebbissimo', 'author_id': 2135504, 'author_profile': 'https://Stackoverflow.com/users/2135504', 'pm_score': 1, 'selected': False, 'text': '<p>If you don\'t have a 3.7 for @dataclass and need mutability, the following code might work for you. It\'s quite self-documenting and IDE-friendly (auto-complete), prevents writing things twice, is easily extendable and it is very simple to test that all instance variables are completely initialized:</p>\n\n<pre><code>class Params():\n    def __init__(self):\n        self.var1 : int = None\n        self.var2 : str = None\n\n    def are_all_defined(self):\n        for key, value in self.__dict__.items():\n            assert (value is not None), "instance variable {} is still None".format(key)\n        return True\n\n\nparams = Params()\nparams.var1 = 2\nparams.var2 = \'hello\'\nassert(params.are_all_defined)\n</code></pre>\n'}, {'answer_id': 55591469, 'author': 'jochen', 'author_id': 648741, 'author_profile': 'https://Stackoverflow.com/users/648741', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a solution which uses a class (never instantiated) to hold data.  I like that this way involves very little typing and does not require any additional packages <em>etc.</em></p>\n\n<pre><code>class myStruct:\n    field1 = "one"\n    field2 = "2"\n</code></pre>\n\n<p>You can add more fields later, as needed:</p>\n\n<pre><code>myStruct.field3 = 3\n</code></pre>\n\n<p>To get the values, the fields are accessed as usual:</p>\n\n<pre><code>&gt;&gt;&gt; myStruct.field1\n\'one\'\n</code></pre>\n'}, {'answer_id': 58118444, 'author': 'calandoa', 'author_id': 26074, 'author_profile': 'https://Stackoverflow.com/users/26074', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a quick and dirty trick:</p>\n\n<pre><code>&gt;&gt;&gt; ms = Warning()\n&gt;&gt;&gt; ms.foo = 123\n&gt;&gt;&gt; ms.bar = \'akafrit\'\n</code></pre>\n\n<p>How does it works? It just re-use the builtin class <code>Warning</code> (derived from <code>Exception</code>) and use it as it was you own defined class.</p>\n\n<p>The good points are that you do not need to import or define anything first, that "Warning" is a short name, and that it also makes clear you are doing something dirty which should not be used elsewhere than a small script of yours.</p>\n\n<p>By the way, I tried to find something even simpler like <code>ms = object()</code> but could not (this last exemple is not working). If you have one, I am interested.</p>\n'}, {'answer_id': 61660221, 'author': 'Tioneb', 'author_id': 8484485, 'author_profile': 'https://Stackoverflow.com/users/8484485', 'pm_score': 1, 'selected': False, 'text': '<p>The best way I found to do this was to use a custom dictionary class as explained in this post: <a href="https://stackoverflow.com/a/14620633/8484485">https://stackoverflow.com/a/14620633/8484485</a></p>\n\n<p>If iPython autocompletion support is needed, simply define the <strong>dir</strong>() function like this:</p>\n\n<pre class="lang-py prettyprint-override"><code>class AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init__(*args, **kwargs)\n        self.__dict__ = self\n    def __dir__(self):\n        return self.keys()\n</code></pre>\n\n<p>You then define your pseudo struct like so: (this one is nested)</p>\n\n<pre><code>my_struct=AttrDict ({\n    \'com1\':AttrDict ({\n        \'inst\':[0x05],\n        \'numbytes\':2,\n        \'canpayload\':False,\n        \'payload\':None\n    })\n})\n</code></pre>\n\n<p>You can then access the values inside my_struct like this:</p>\n\n<p><code>print(my_struct.com1.inst)</code></p>\n\n<p>=><code>[5]</code></p>\n'}, {'answer_id': 62212859, 'author': 'Carson', 'author_id': 9935654, 'author_profile': 'https://Stackoverflow.com/users/9935654', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple" rel="nofollow noreferrer">NamedTuple</a> is comfortable. but there no one shares the performance and storage.</p>\n\n<pre class="lang-py prettyprint-override"><code>from typing import NamedTuple\nimport guppy  # pip install guppy\nimport timeit\n\n\nclass User:\n    def __init__(self, name: str, uid: int):\n        self.name = name\n        self.uid = uid\n\n\nclass UserSlot:\n    __slots__ = (\'name\', \'uid\')\n\n    def __init__(self, name: str, uid: int):\n        self.name = name\n        self.uid = uid\n\n\nclass UserTuple(NamedTuple):\n    # __slots__ = ()  # AttributeError: Cannot overwrite NamedTuple attribute __slots__\n    name: str\n    uid: int\n\n\ndef get_fn(obj, attr_name: str):\n    def get():\n        getattr(obj, attr_name)\n    return get\n</code></pre>\n\n<pre><code>if \'memory test\':\n    obj = [User(\'Carson\', 1) for _ in range(1000000)]      # Cumulative: 189138883\n    obj_slot = [UserSlot(\'Carson\', 1) for _ in range(1000000)]          # 77718299  &lt;-- winner\n    obj_namedtuple = [UserTuple(\'Carson\', 1) for _ in range(1000000)]   # 85718297\n    print(guppy.hpy().heap())  # Run this function individually. \n    """\n    Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)\n     0 1000000    24 112000000 34 112000000  34 dict of __main__.User\n     1 1000000    24 64000000  19 176000000  53 __main__.UserTuple\n     2 1000000    24 56000000  17 232000000  70 __main__.User\n     3 1000000    24 56000000  17 288000000  87 __main__.UserSlot\n     ...\n    """\n\nif \'performance test\':\n    obj = User(\'Carson\', 1)\n    obj_slot = UserSlot(\'Carson\', 1)\n    obj_tuple = UserTuple(\'Carson\', 1)\n\n    time_normal = min(timeit.repeat(get_fn(obj, \'name\'), repeat=20))\n    print(time_normal)  # 0.12550550000000005\n\n    time_slot = min(timeit.repeat(get_fn(obj_slot, \'name\'), repeat=20))\n    print(time_slot)  # 0.1368690000000008\n\n    time_tuple = min(timeit.repeat(get_fn(obj_tuple, \'name\'), repeat=20))\n    print(time_tuple)  # 0.16006120000000124\n\n    print(time_tuple/time_slot)  # 1.1694481584580898  # The slot is almost 17% faster than NamedTuple on Windows. (Python 3.7.7)\n\n</code></pre>\n\n<p>If your <code>__dict__</code> is not using, please choose between <code>__slots__</code> (higher performance and storage) and <code>NamedTuple</code> (clear for reading and use)</p>\n\n<p><em>You can review this link(<a href="https://stackoverflow.com/questions/472000/usage-of-slots">Usage of <strong>slots</strong>\n</a>) to get more <code>__slots__</code> information.</em></p>\n'}]
['https://Stackoverflow.com/questions/35988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3738/']