Workaround for documenting Enum __new__ methods #14489
ipilcher
started this conversation in
Show and tell
Replies: 1 comment
|
I already use too many Enum workarounds that for this use case I'd simply copy-paste anything necessary verbatin into the rst declaration to at least have explicit control and simplify the problem. But knowing there's a dynamic fix is interesting. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Python enums (
enum.Enumand its subclasses) have an annoying behavior. When creating an enum type, theEnumTypemetaclass replaces the orginal__new__method, and it doesn't copy the docstring from the original__new__to the replacement. This obviously prevents Sphinx autodoc from finding it.Dropping the code snippet below into
conf.pyfixes this. It retrieves the orginal docstring from the enum type's_new_member_attribute (which is the original__new__method) and replaces the automatically retrieved docstring (usuallyNone) with the original one.The only part that isn't straightforward is tracking down the enum type's actual class object. Sphinx doesn't pass this in, and it isn't directly available from the method object. We have to parse the methods fully-qualified name and figure out where the module name ends and the class name begins (which isn't obvious in the case of a nested class). Thus, we start with the longest possible module name and shorten it one element at a time until we find a name that actually represents a module. From there, we start at the module namespace and recurse through the components of the class name (enclosing classes) until we arrive at the actual enum type class.
All reactions