Dzung Nguyen
Dzung Nguyen

Reputation: 3944

Define a constant object in python

I defined a class Factor in the file factor.py:

class Factor:
    def __init__(self, var, value):
        self.var = var          # hold variable names
        self.value = value  # hold probability values

For convenience and code cleanliness, I want to define a constant variable and be able to access it as Factor.empty

 empty = Factor([], None)

What is the common way to do this? Should I put in the class definition, or outside? I'm thinking of putting it outside the class definition, but then I wouln't be able to refer to it as Factor.empty then.

Upvotes: 3

Views: 2779

Answers (1)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

If you want it outside the class definition, just do this:

class Factor:
    ...

Factor.empty = Factor([], None)

But bear in mind, this isn't a "constant". You could easily do something to change the value of empty or its attributes. For example:

Factor.empty = something_else

Or:

Factor.empty.var.append("a value")

So if you pass Factor.empty to any code that manipulates it, you might find it less empty than you wanted.


One solution to that problem is to re-create a new empty Factor each time someone accesses Factor.empty:

class FactorType(type):
    @property
    def empty(cls):
        return Factor([], None)

class Factor(object):
    __metaclass__ = FactorType
    ...

This adds an empty property to the Factor class. You are safe to do what you want with it, as every time you access empty, a new empty Factor is created.

Upvotes: 5

Related Questions