views:

103

answers:

3

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

+1  A: 

yes. place the code in the__init__ function

class Foo(object):
    def __init__(self):
        self.other = Bar

class Bar(object):
    def __init__(self):
      self.other = Foo

if __name__ == '__main__':
    print 'all ok'
aaronasterling
what code exactly?
sharvey
the code that assigns the class attributes. see my edits
aaronasterling
This doesn't do quite what the OP asked for, but it may be what the OP actually *wants*. The example in the question sets Foo.other and Bar.other as class properties, not as instance properties. Whether that was the right thing to do is up to the OP.
Dan Breslau
They are in fact class properties, I updated the question.
sharvey
+5  A: 

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.

zvonimir
Beat me by a few seconds... :-)
Dan Breslau
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
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.
zvonimir
@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.
Ignacio Vazquez-Abrams
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
+1  A: 

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.

Dan Breslau
I'll update the question. Sorry if it was vague.
sharvey