Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct objects in python

Tags:

python

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 ?

like image 245
Stefano Borini Avatar asked Dec 10 '09 04:12

Stefano Borini


People also ask

What is a struct in Python?

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.

Can we use struct 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.

What is the equivalent of struct in Python?

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.

What is struct unpack in Python?

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.


1 Answers

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()...;-).

like image 135
Alex Martelli Avatar answered Sep 27 '22 18:09

Alex Martelli