2

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).

2 Answers 2

10

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.

6
  • Beat me by a few seconds... :-) Jul 17, 2010 at 3:07
  • 1
    This is used with sqlalchemy to create relations between models, the doc seems to point to such a design (the doc for flask to be precise), that solution seems a weird.
    – sharvey
    Jul 17, 2010 at 3:13
  • 1
    AFAIK sqlalchemy uses string references for foreign keys and avoids this problem that way, but maybe there are some cases where you need to do this.
    – zvone
    Jul 17, 2010 at 3:21
  • 1
    @sharvey: That is important information that belongs in the question. Most ORMs have a proper way to resolve such a situation, but we can't tell you that if we don't know that it's what you need. Jul 17, 2010 at 3:21
  • 1
    Yeah but I wanted to see if there was a solution to the more general problem first, before settling for a sqlachemy specific solution.
    – sharvey
    Jul 17, 2010 at 3:48
1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.