Question

I have the following class with inner class and class variable:

class MyForm(forms.ModelForm):

    type_constant = 'type'

    class Meta:

        model = Customer
        fields = ('type')

I would like to replace 'type' in the fields variable to the type constant in the super class. How do I use the type_constant in the fields variable value?

Was it helpful?

Solution

One way is to pass the outer class member as a parameter. I see no better way as far as I know. The inter class has no information about which class includes it. And python has not offer any specific keywords or methods for outer class accessing. So it is better to do it with parameter passing.

__init__(self, other=None)

in inter class.

OTHER TIPS

You can solve it using frame inspection:

import inspect

def get_enclosing(name):
    # get the frame where the enclosing class in construction is evaluated
    outerframe = inspect.getouterframes(inspect.currentframe())[2][0]
    return outerframe.f_locals[name]

class Customer(object):
    pass
class MyForm(object):

    type_constant = 'type'

    class Meta:

        model = Customer
        fields = get_enclosing('type_constant')

Then:

>>> MyForm.Meta.fields
'type'

Note 1: I'm using feature documented in the inspect module (see http://docs.python.org/2/library/inspect.html). Most probably, this will only work in CPython.

Note 2: unless you really need some magic, parameter passing is probably the right way to do it. I posted my answer to show that it is feasible, but I won't consider it as good code, unless you have a strong reason to avoid passing info from the outer class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top