sharvey
sharvey

Reputation: 8145

Python circular references

trying to have two class that reference each others, in the same file. What would be the best way to have this working:

class Foo(object):
    other = Bar

class Bar(object):
    other = Foo

if __name__ == '__main__':
    print 'all ok'

?

The problem seems to be that since the property is on the class, since it tries to executes as soon as the class itself is parsed.

Is there a way to solve that?

edit:

those keys are used for SQLAlchemy mapping, to they realy are class variables (not instance).

Upvotes: 2

Views: 5053

Answers (2)

Dan Breslau
Dan Breslau

Reputation: 11522

Assuming that you really want Foo.other and Bar.other to be class properties, rather than instance properties, then this works (I tested, just to be sure) :

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

If it's instance properties that you're after, then aaronasterling's answer is more appropriate.

Upvotes: 1

zvone
zvone

Reputation: 19352

This would do what you want:

class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

I would prefer to avoid such design completely, though.

Upvotes: 10

Related Questions