Two questions about __set_name__

  1. I’ve noticed that several libraries, for various reasons, use a “stringified” variable name in invocations. E.g. x = sympy.Symbol("x", ...) or Cls = namedtuple("Cls", ...). Question: how feasible is it to call __set_name__ for those objects in a module’s namespace?

  2. Why is __set_name__ called after the class block rather than on namespace.__setitem__? I’ve noticed on a couple occasions with nested decorators that it would be nice to have the parent’s name available to the child. I think this is a matter of pre/in/postorder recursion, and currently only the postorder is available? I’m aware I can use a custom metaclass namespace through __prepare__ to get inorder, and I believe preorder isn’t possible because the object wouldn’t exist yet.

  1. I believe calling __set_name__ is close to impossible since neither the compiler nor the interpreter can reliably tell the difference between an imported value rebound to the global namespace of a different module or a newly constructed value that belongs in this module. Calling __set_name__ always could technically work, but then the objects have to be careful where they belong and somehow have to deal with having multiple names, but without a clear owner relationship.

  2. Even if __set_name__ would be called on name binding, I don’t believe it would be available on chained decorators since it’s only assigned after everything happened. It would potentially also be a bit more confusing if you have decorators like property that could reasonably be attached to the same name multiple times. Although I don’t quite understand what you mean with recursion in this context.