How to implement a union (C data type) in Python?

Stephen Horne steve at ninereeds.fsnet.co.uk
Mon Mar 8 14:40:10 EST 2004


On 8 Mar 2004 07:53:59 -0800, lamote1 at netscape.net (chads) wrote:

>How would one implement a union (C data type) in Python, given this
>simple example?
>
>union {
>   struct {
>      int size;
>      float time;
>   } var1;
>   struct {
>      char initial;
>      float time;
>   } var2;
>};

First thought is that you simply don't need it.

One reason for using a union is simply to save on memory from
redundant fields. If this is the case, Pythons dynamic nature means
that you can add or remove any field you want from most objects at any
time. For instance...

  class myobject (object) :
    pass

  o = myobject()

  #  Set first pair of fields
  o.size = 1
  o.type = 2.3

  #  Replace with second pair of fields
  del o.size, o.type

  o.initial = 'a'
  o.time    = 3.4

The memory savings for this are probably not a big concern, but there
are benefits in terms of introspection - the fact that a field isn't
present can be useful information in itself.

OTOH, if the reason is to get overlapping binary representations, this
kind of memory layout dependence is intentionally not an issue in
Python. Though there is a 'struct' library for those jobs where
dealing with packed binary data is essential, such as handling binary
file formats.
  

-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk



More information about the Python-list mailing list