Search code examples
pythonclassmethodscvxpy

Nested method in a class in Python


I'm using a software package for optimization called CVX. It has these "atoms" which take a CVX expression and construct a new CVX expression. One example is the trace atom to compute the trace of a matrix.

I thought I would need code as below to create a CVX variable (an n by n matrix) and compute its trace

X = cvxpy.Variable((n,n))
tr = cvxpy.atoms.affine.trace.trace(X)

This does work but what also works is simply

X = cvxpy.Variable((n,n))
tr = cvxpy.trace(X)

Why does the second option work? In general, when there is a class with nested methods, how am I able to call an inner method directly in Python?


Solution

  • I wouldn't generalize the behavior. Almost certainly this is done by design. Likely the lib devs didn't want to have to be so verbose with tracing down the hierarchy so gave you this shortcut. It's also possible (very likely) that the .trace directly against the cvxpy object is operating on that object itself whereas the deeper one is acting on the cvxpy.atoms.affine.trace object.

    Be very careful because the side effects may not be the same.

    To answer your question very directly I'd suggest that the second option works because somebody thought to make their API easier OR it just happens to work the way you're expecting.

    To your second question: nested methods aren't a thing. There is a property of the cvxpy object called atoms which in turn has a property called affine which has a method called trace.