empty classes as c structs?

Alan McIntyre alan.mcintyre at esrgtech.com
Fri Feb 4 14:25:53 EST 2005


Christopher,

I've found myself doing the same thing.  You could do something like this:

blah = type('Struct', (), {})()
blah.some_field = x

I think I'd only do this if I needed to construct objects at runtime 
based on information that I don't have at compile time, since the two 
lines of code for your empty class would probably be more recognizable 
to more people.

If this usage of type() strikes anyone as inappropriate please let me 
know, because I really don't know. :)

Christopher J. Bottaro wrote:
> I find myself doing the following very often:
> 
> class Struct:
>         pass
> ...
> blah = Struct()
> blah.some_field = x
> blah.other_field = y
> ...
> 
> Is there a better way to do this?  Is this considered bad programming
> practice?  I don't like using tuples (or lists) because I'd rather use
> symbolic names, rather than numeric subscripts.  Also, I don't like having
> to declare the empty Struct class everytime I want to do this (which is
> very often).
> 
> Feedback is appreciated, thanks.
> 



More information about the Python-list mailing list