I wanted to create a throwaway "struct" object to keep various status flags. My first approach was this (javascript style)
>>> status = object()
>>> status.foo = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
Definitely not what I expected, because this works:
>>> class Anon: pass
...
>>> b=Anon()
>>> b.foo = 4
I guess this is because object() does not have a __dict__
. I don't want to use a dictionary, and assuming I don't want to create the Anon object, is there another solution ?
The struct module in Python is used to convert native Python data types such as strings and numbers into a string of bytes and vice versa. What this means is that users can parse binary files of data stored in C structs in Python.
The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3. The struct module is related to the C languages.
Python does not exactly have the same thing as a struct in Matlab. You can achieve something like it by defining an empty class and then defining attributes of the class. You can check if an object has a particular attribute using hasattr.
unpack() This function unpacks the packed value into its original representation with the specified format. This function always returns a tuple, even if there is only one element.
The most concise way to make "a generic object to which you can assign/fetch attributes" is probably:
b = lambda:0
As most other answers point out, there are many other ways, but it's hard to beat this one for conciseness (lambda:0
is exactly the same number of characters as object()
...;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With