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

Miki Tebeka miki.tebeka at zoran.com
Mon Mar 8 11:42:02 EST 2004


Hello Chad,

> 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;
> };
You can't, but you're thinking in C and not in Python ;-)

Python variables are dynamically typed, this means
a = 100
a = "Hello"
a = lambda x: x * 2

Is OK in Python.

You should use classes where you use structs in C
class var1:
     def __init__(self, size, time):
         self.size = size
         self.time = time
class var2:
     def __init__(self, initial, time):
         self.initial = initial
         self.time = time

And to check the type of variable you can use `isinstance' function.
I don't recommend using the above, have each function return one type of 
object only. Unions were created to same memory, Python is the wrong 
language for such optimizations. If you need to save memory using unions 
I suggest coding in C and using SWIG/Boost.Python to export the C module 
to Python.

HTH.
Miki



More information about the Python-list mailing list