I'm writing a Math equation solver in python (for fun). The first design that came to my mind:

  • Expression: base class for every item in an equation (maybe bad name).
  • BinaryExpression extends Expression: two expressions with a sign.
  • Expression + Expression should provide a BinaryExpression, I do this through overriding the __add__ method of Expression.

this is sort of circular dependency, which me and python both hates.

class Expression(object):
    def __add__(self, other):
        return BinaryExpresison(self, OP.ADD, other)

class BinaryExpress(Expression):
    def __init__(self, op, other):
        pass # super and staff

How would you do it?

  • 2
    Python has no problems with your circular dependency here. – Martijn Pieters Sep 29 '14 at 18:03
  • However, I don't quite see why BinaryExpression is to be a subclass. Python's AST makes Expression a top-level statement (inherits from ast.mod) while BinOp is a subclass of ast.expr. – Martijn Pieters Sep 29 '14 at 18:06
  • BinOp is an Expression, because BinOp + BinOp should be a BinOp. – TheAnosmic Sep 30 '14 at 8:44
  • The Python AST actually has 3 'expression' types; the ast.mod subclass (a top-level program can consist of just the one expression), the expression statement (a full program consists only of ast.stmt types), and the AST.expr subclasses, which are the components of an expression. – Martijn Pieters Sep 30 '14 at 8:50

How would you do it?

I'm not familiar with Python, but that sort of construct to build a composite or decorator pattern is something I've done a few times (albeit in C# and C++). It makes for a very nice interface and very usable code.

As long as you consider the BinaryExpression and similar composite/decorators part of the core library/API that everyone will want/use, that design perfectly fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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