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: init subclass docstring formatting for iterators #460

Merged
merged 3 commits into from
Nov 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions a_sync/iter.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import inspect
import logging
import sys
import weakref
from copy import deepcopy
from types import FunctionType
from typing import _GenericAlias, get_args

Expand Down Expand Up @@ -174,11 +175,13 @@ class _AwaitableAsyncIterableMixin(AsyncIterable[T]):
# Update method docstrings by redefining methods
# This is necessary because, by default, subclasses inherit methods from their bases
# which means if we just update the docstring we might edit docs for unrelated objects
is_function = lambda obj: isinstance(obj, (FunctionType, property)) or "cython_function_or_method" in type(obj).__name__

cdef dict functions_to_redefine = {
attr_name: attr_value
for attr_name in dir(cls)
if (attr_value := getattr(cls, attr_name, None))
and isinstance(attr_value, FunctionType)
and is_function(attr_value)
and attr_value.__doc__
and any(pattern in attr_value.__doc__ for pattern in _FORMAT_PATTERNS)
}
Expand All @@ -187,19 +190,23 @@ class _AwaitableAsyncIterableMixin(AsyncIterable[T]):
cdef object function_obj
for function_name, function_obj in functions_to_redefine.items():
# Create a new function object with the docstring formatted appropriately for this class
redefined_function_obj = FunctionType(
function_obj.__code__,
function_obj.__globals__,
name=function_obj.__name__,
argdefs=function_obj.__defaults__,
closure=function_obj.__closure__,
)
#redefined_function_obj = FunctionType(
# function_obj.__code__,
# function_obj.__globals__,
# name=function_obj.__name__,
# argdefs=function_obj.__defaults__,
# closure=function_obj.__closure__,
#)
redefined_function_obj = deepcopy(function_obj)

redefined_function_obj.__doc__ = function_obj.__doc__.format(
cls=cls.__name__,
obj=type_string,
)

if "{cls}" in redefined_function_obj.__doc__:
raise ValueError(redefined_function_obj.__doc__)

setattr(cls, function_name, redefined_function_obj)

return super().__init_subclass__(**kwargs)
Expand Down
Loading