Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the inspect bug by generating a __signature__ with a descriptor. #19

Merged
merged 2 commits into from
Jun 25, 2024

Conversation

DavidCEllis
Copy link
Owner

inspect.signature appears to call the __get__ method of __init__ descriptors incorrectly.

For:

from ducktools.classbuilder import AnnotationClass

class Demo(AnnotationClass):
    x: int

Demo.__init__ will call the descriptor with (None, Demo).

demo = Demo(...) will call the descriptor with (demo, Demo)

inspect.signature(Demo) will call the descriptor with (Demo, type(Demo)) which is incorrect in this case.

If __init__ is already generated through regular access then inspect.signature will work correctly.

To work around this currently the descriptor checks if the second argument is a metaclass (subclass of 'type') and uses the first argument. This prevents the descriptor generator from being used for metaclasses. I don't have a specific use for it but I can see that potentially it could be used to generate metaclass methods.

The new fix instead provides a descriptor for __signature__. Inspect will look at this before trying to figure out the signature itself. This descriptor forces the generation of __init__, removes itself from the class and then calls inspect.signature on the class again to get the correct signature, which is then stored on __signature__ of the class and returned.

@DavidCEllis DavidCEllis merged commit ce5297b into main Jun 25, 2024
8 checks passed
@DavidCEllis DavidCEllis deleted the better_inspect_detection branch June 25, 2024 17:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant