Should enum values be class instances? Or is this inefficient?

Fredrik Lundh effbot at telia.com
Wed Aug 30 03:15:27 EDT 2000


tom wrote:
> Will this consume huge amounts of memory (one instance of the enum class for
> every enum variable) or will the interpreter only create as many instances
> as there are unique values of the enumeration?

judging from fred's code, the latter.

everything is a reference in python, and python never copies
objects by itself.

> So, I want to have value in my class that refers to an enumeration which has
> 6 unique enumerators.  My program might create 1000 instances of this class.
> So each of the 1000 instances of my class will have a reference to an
> instance of the enumeration class.  (That's 1000 references, but I assume
> that references don't take too much memory.)   Will Python create 6
> instances of the enumeration class, or 1000?

neither.

assuming you only call the "enum" constructor once (to create
the enumeration), you'll end up with one enumeration instance,
six values stored inside it, and any number of pointers to those
values.

    # create one object with six values
    lang = enum("python", "java", "c++", "sh", "tcl", "assembler")

    # create a couple of objects
    for i in range(10000):
        # add reference to a value maintained by lang
        # (but not to lang itself)
        obj = myclass(lang.python)

:::

> Instances are mutable aren't they?  And Python only invokes this efficiency
> for immutables doesn't it?

python doesn't care -- it's up to the type implementation to
reuse values, if it knows that they can never be changed in
place.  (and the easiest way to do that is to make sure you
don't have any methods ;-)

:::

personally, I find enumerations being rather un-pythonish (why
not just use named constants in namespaces), but that's another
story.  

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->




More information about the Python-list mailing list