3

I have a scenario where I've got multiple nested classes all with the same name, and debugging it is driving me nuts.

Here's a sketch:

class Reference(object):
    # common functionality here

class Fruit(object):
    # common functionality here

class Apple(Fruit):
    class Ref(Reference):
        # specific functionality here

class Orange(Fruit):
    class Ref(Reference):
        # specific functionality here

# like 6 more fruits

My problem: any operation that lists the classname of a reference object shows it as mymodule.Ref and not, say, mymodule.Apple.Ref, which would be much more helpful.

Is there a way to tell Python to use a better name for instances of my nested classes? in default __str__ but also in __type__, etc.

Bonus details:

  • flattening the class structure and/or using unique names would do it, but (a) that adds namespace clutter, and (b) there are bits in Fruit that use cls.Ref/self.Ref. Suboptimal.
  • it's a legacy 2.7 research system, if that matters. Actually, if 3 has fixed this that would be a useful addition to my bucket of arguments to upgrade us...
2
  • This just isn't something you would ever do in Python. Commented Mar 18, 2019 at 20:30
  • @DanielRoseman Django does it with the nested class Meta. Commented Mar 19, 2019 at 16:17

1 Answer 1

2

Actually Python 3 did fix this with __qualname__. Time to upgrade.

https://www.python.org/dev/peps/pep-3155/#example-with-nested-classes

According to the PEP rationale (PEP 3155 -- Qualified name for classes and functions), what you want is not possible in 2.7.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.