index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
707,516
pybind11_stubgen.parser.mixins.fix
handle_method
null
def handle_method(self, path: QualifiedName, method: Any) -> list[Method]: result = super().handle_method(path, method) return [ m for m in result if not ( m.function.name == "__init__" and m.function.doc == object.__init__.__doc__ ) ]
(self, path: pybind11_stubgen.structs.QualifiedName, method: Any) -> list[pybind11_stubgen.structs.Method]
707,526
pybind11_stubgen.parser.mixins.fix
FixScipyTypeArguments
null
class FixScipyTypeArguments(IParser): def parse_annotation_str( self, annotation_str: str ) -> ResolvedType | InvalidExpression | Value: result = super().parse_annotation_str(annotation_str) if not isinstance(result, ResolvedType): return result # scipy.sparse arrays/matrices are not currently generic and do not accept type # arguments if result.name[:2] == ("scipy", "sparse"): result.parameters = None return result
()
707,543
pybind11_stubgen.parser.mixins.fix
parse_annotation_str
null
def parse_annotation_str( self, annotation_str: str ) -> ResolvedType | InvalidExpression | Value: result = super().parse_annotation_str(annotation_str) if not isinstance(result, ResolvedType): return result # scipy.sparse arrays/matrices are not currently generic and do not accept type # arguments if result.name[:2] == ("scipy", "sparse"): result.parameters = None return result
(self, annotation_str: str) -> pybind11_stubgen.structs.ResolvedType | pybind11_stubgen.structs.InvalidExpression | pybind11_stubgen.structs.Value
707,547
pybind11_stubgen.parser.mixins.fix
FixTypingTypeNames
null
class FixTypingTypeNames(IParser): __typing_names: set[Identifier] = set( Identifier(name) for name in ( "Annotated", "Any", "Buffer", "Callable", "Dict", "ItemsView", "Iterable", "Iterator", "KeysView", "List", "Literal", "Optional", "Sequence", "Set", "Tuple", "Union", "ValuesView", # Old pybind11 annotations were not capitalized "buffer", "iterable", "iterator", "sequence", ) ) __typing_extensions_names: set[Identifier] = set( Identifier(name) for name in ( "buffer", "Buffer", ) ) def __init__(self): super().__init__() if sys.version_info < (3, 9): self.__typing_extensions_names.add(Identifier("Annotated")) if sys.version_info < (3, 8): self.__typing_extensions_names.add(Identifier("Literal")) def parse_annotation_str( self, annotation_str: str ) -> ResolvedType | InvalidExpression | Value: result = super().parse_annotation_str(annotation_str) return self._parse_annotation_str(result) def _parse_annotation_str( self, result: ResolvedType | InvalidExpression | Value ) -> ResolvedType | InvalidExpression | Value: if not isinstance(result, ResolvedType): return result result.parameters = ( [self._parse_annotation_str(p) for p in result.parameters] if result.parameters is not None else None ) if len(result.name) != 1: return result word = result.name[0] if word in self.__typing_names: package = "typing" if word in self.__typing_extensions_names: package = "typing_extensions" result.name = QualifiedName.from_str( f"{package}.{word[0].upper()}{word[1:]}" ) if word == "function" and result.parameters is None: result.name = QualifiedName.from_str("typing.Callable") if word in ("object", "handle") and result.parameters is None: result.name = QualifiedName.from_str("typing.Any") return result
()
707,548
pybind11_stubgen.parser.mixins.fix
__init__
null
def __init__(self): super().__init__() if sys.version_info < (3, 9): self.__typing_extensions_names.add(Identifier("Annotated")) if sys.version_info < (3, 8): self.__typing_extensions_names.add(Identifier("Literal"))
(self)
707,549
pybind11_stubgen.parser.mixins.fix
_parse_annotation_str
null
def _parse_annotation_str( self, result: ResolvedType | InvalidExpression | Value ) -> ResolvedType | InvalidExpression | Value: if not isinstance(result, ResolvedType): return result result.parameters = ( [self._parse_annotation_str(p) for p in result.parameters] if result.parameters is not None else None ) if len(result.name) != 1: return result word = result.name[0] if word in self.__typing_names: package = "typing" if word in self.__typing_extensions_names: package = "typing_extensions" result.name = QualifiedName.from_str( f"{package}.{word[0].upper()}{word[1:]}" ) if word == "function" and result.parameters is None: result.name = QualifiedName.from_str("typing.Callable") if word in ("object", "handle") and result.parameters is None: result.name = QualifiedName.from_str("typing.Any") return result
(self, result: pybind11_stubgen.structs.ResolvedType | pybind11_stubgen.structs.InvalidExpression | pybind11_stubgen.structs.Value) -> pybind11_stubgen.structs.ResolvedType | pybind11_stubgen.structs.InvalidExpression | pybind11_stubgen.structs.Value
707,566
pybind11_stubgen.parser.mixins.fix
parse_annotation_str
null
def parse_annotation_str( self, annotation_str: str ) -> ResolvedType | InvalidExpression | Value: result = super().parse_annotation_str(annotation_str) return self._parse_annotation_str(result)
(self, annotation_str: str) -> pybind11_stubgen.structs.ResolvedType | pybind11_stubgen.structs.InvalidExpression | pybind11_stubgen.structs.Value
707,570
pybind11_stubgen.parser.mixins.fix
FixValueReprRandomAddress
repr examples: <capsule object NULL at 0x7fdfdf8b5f20> # PyCapsule <foo.bar.Baz object at 0x7fdfdf8b5f20>
class FixValueReprRandomAddress(IParser): """ repr examples: <capsule object NULL at 0x7fdfdf8b5f20> # PyCapsule <foo.bar.Baz object at 0x7fdfdf8b5f20> """ _pattern = re.compile( r"<(?P<name>[\w.]+) object " r"(?P<capsule>\w+\s)*at " r"(?P<address>0x[a-fA-F0-9]+)>" ) def handle_value(self, value: Any) -> Value: result = super().handle_value(value) result.repr = self._pattern.sub(r"<\g<name> object>", result.repr) return result
()
707,586
pybind11_stubgen.parser.mixins.fix
handle_value
null
def handle_value(self, value: Any) -> Value: result = super().handle_value(value) result.repr = self._pattern.sub(r"<\g<name> object>", result.repr) return result
(self, value: Any) -> pybind11_stubgen.structs.Value
707,591
pybind11_stubgen.parser.interface
IParser
null
class IParser(abc.ABC): @abc.abstractmethod def handle_alias(self, path: QualifiedName, origin: Any) -> Alias | None: ... @abc.abstractmethod def handle_attribute(self, path: QualifiedName, attr: Any) -> Attribute | None: ... @abc.abstractmethod def handle_bases( self, path: QualifiedName, bases: tuple[type, ...] ) -> list[QualifiedName]: ... @abc.abstractmethod def handle_class(self, path: QualifiedName, class_: type) -> Class | None: ... @abc.abstractmethod def handle_class_member( self, path: QualifiedName, class_: type, obj: Any ) -> Docstring | Alias | Class | list[Method] | Field | Property | None: ... @abc.abstractmethod def handle_docstring(self, path: QualifiedName, doc: Any) -> Docstring | None: ... @abc.abstractmethod def handle_field(self, path: QualifiedName, field: Any) -> Field | None: ... @abc.abstractmethod def handle_function(self, path: QualifiedName, func: Any) -> list[Function]: ... @abc.abstractmethod def handle_import(self, path: QualifiedName, origin: Any) -> Import | None: ... @abc.abstractmethod def handle_method(self, path: QualifiedName, method: Any) -> list[Method]: ... @abc.abstractmethod def handle_module( self, path: QualifiedName, module: types.ModuleType ) -> Module | None: ... @abc.abstractmethod def handle_module_member( self, path: QualifiedName, module: types.ModuleType, obj: Any ) -> ( Docstring | Import | Alias | Class | list[Function] | Attribute | Module | None ): ... @abc.abstractmethod def handle_property(self, path: QualifiedName, prop: Any) -> Property | None: ... @abc.abstractmethod def handle_type(self, type_: type) -> QualifiedName: ... @abc.abstractmethod def handle_value(self, value: Any) -> Value: ... @abc.abstractmethod def parse_args_str(self, args_str: str) -> list[Argument]: ... @abc.abstractmethod def parse_annotation_str( self, annotation_str: str ) -> ResolvedType | InvalidExpression | Value: ... @abc.abstractmethod def parse_value_str(self, value: str) -> Value | InvalidExpression: ... @abc.abstractmethod def report_error(self, error: ParserError) -> None: ... @abc.abstractmethod def finalize(self): ...
()
707,612
pybind11_stubgen.parser.mixins.error_handlers
IgnoreAllErrors
null
class IgnoreAllErrors(IParser): def report_error(self, error: ParserError): return None
()
707,632
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): return None
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,633
pybind11_stubgen.parser.mixins.error_handlers
IgnoreInvalidExpressionErrors
null
class IgnoreInvalidExpressionErrors(IParser): def __init__(self): super().__init__() self.__regex: re.Pattern | None = None def set_ignored_invalid_expressions(self, regex: re.Pattern): self.__regex = regex def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, InvalidExpressionError): if self.__regex.match(error.expression): return super().report_error(error)
()
707,634
pybind11_stubgen.parser.mixins.error_handlers
__init__
null
def __init__(self): super().__init__() self.__regex: re.Pattern | None = None
(self)
707,654
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, InvalidExpressionError): if self.__regex.match(error.expression): return super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,655
pybind11_stubgen.parser.mixins.error_handlers
set_ignored_invalid_expressions
null
def set_ignored_invalid_expressions(self, regex: re.Pattern): self.__regex = regex
(self, regex: re.Pattern)
707,656
pybind11_stubgen.parser.mixins.error_handlers
IgnoreInvalidIdentifierErrors
null
class IgnoreInvalidIdentifierErrors(IParser): def __init__(self): super().__init__() self.__regex: re.Pattern | None = None def set_ignored_invalid_identifiers(self, regex: re.Pattern): self.__regex = regex def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, InvalidIdentifierError): if self.__regex.match(str(error.name)): return super().report_error(error)
()
707,677
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, InvalidIdentifierError): if self.__regex.match(str(error.name)): return super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,678
pybind11_stubgen.parser.mixins.error_handlers
set_ignored_invalid_identifiers
null
def set_ignored_invalid_identifiers(self, regex: re.Pattern): self.__regex = regex
(self, regex: re.Pattern)
707,679
pybind11_stubgen.parser.mixins.error_handlers
IgnoreUnresolvedNameErrors
null
class IgnoreUnresolvedNameErrors(IParser): def __init__(self): super().__init__() self.__regex: re.Pattern | None = None def set_ignored_unresolved_names(self, regex: re.Pattern): self.__regex = regex def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, NameResolutionError): if self.__regex.match(str(error.name)): return super().report_error(error)
()
707,700
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): if self.__regex is not None: if isinstance(error, NameResolutionError): if self.__regex.match(str(error.name)): return super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,701
pybind11_stubgen.parser.mixins.error_handlers
set_ignored_unresolved_names
null
def set_ignored_unresolved_names(self, regex: re.Pattern): self.__regex = regex
(self, regex: re.Pattern)
707,702
pybind11_stubgen.parser.mixins.error_handlers
LogErrors
null
class LogErrors(IParser): def report_error(self: LoggerData, error: ParserError) -> None: error_str = f"In {self.current_path} : {error}" if error_str not in self.reported_errors: logger.error(error_str) self.reported_errors.add(error_str) super().report_error(error)
()
707,722
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self: LoggerData, error: ParserError) -> None: error_str = f"In {self.current_path} : {error}" if error_str not in self.reported_errors: logger.error(error_str) self.reported_errors.add(error_str) super().report_error(error)
(self: pybind11_stubgen.parser.mixins.error_handlers.LoggerData, error: pybind11_stubgen.parser.errors.ParserError) -> NoneType
707,723
pybind11_stubgen.parser.mixins.error_handlers
LoggerData
null
class LoggerData(IParser): def __init__(self): super().__init__() self.stack: list[LocalErrors] = [] def __new_layer(self, path: QualifiedName) -> LocalErrors: return LocalErrors(path, errors=set(), stack=self.stack) def handle_module( self, path: QualifiedName, module: types.ModuleType ) -> Module | None: with self.__new_layer(path): return super().handle_module(path, module) def handle_class(self, path: QualifiedName, class_: type) -> Class | None: with self.__new_layer(path): return super().handle_class(path, class_) def handle_function(self, path: QualifiedName, class_: type) -> list[Function]: with self.__new_layer(path): return super().handle_function(path, class_) def handle_method(self, path: QualifiedName, class_: type) -> list[Method]: with self.__new_layer(path): return super().handle_method(path, class_) @property def current_path(self) -> QualifiedName: assert len(self.stack) != 0 return self.stack[-1].path @property def reported_errors(self) -> set[str]: assert len(self.stack) != 0 return self.stack[-1].errors
()
707,724
pybind11_stubgen.parser.mixins.error_handlers
__new_layer
null
def __new_layer(self, path: QualifiedName) -> LocalErrors: return LocalErrors(path, errors=set(), stack=self.stack)
(self, path: pybind11_stubgen.structs.QualifiedName) -> pybind11_stubgen.parser.mixins.error_handlers.LocalErrors
707,725
pybind11_stubgen.parser.mixins.error_handlers
__init__
null
def __init__(self): super().__init__() self.stack: list[LocalErrors] = []
(self)
707,730
pybind11_stubgen.parser.mixins.error_handlers
handle_class
null
def handle_class(self, path: QualifiedName, class_: type) -> Class | None: with self.__new_layer(path): return super().handle_class(path, class_)
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type) -> pybind11_stubgen.structs.Class | None
707,734
pybind11_stubgen.parser.mixins.error_handlers
handle_function
null
def handle_function(self, path: QualifiedName, class_: type) -> list[Function]: with self.__new_layer(path): return super().handle_function(path, class_)
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type) -> list[pybind11_stubgen.structs.Function]
707,736
pybind11_stubgen.parser.mixins.error_handlers
handle_method
null
def handle_method(self, path: QualifiedName, class_: type) -> list[Method]: with self.__new_layer(path): return super().handle_method(path, class_)
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type) -> list[pybind11_stubgen.structs.Method]
707,737
pybind11_stubgen.parser.mixins.error_handlers
handle_module
null
def handle_module( self, path: QualifiedName, module: types.ModuleType ) -> Module | None: with self.__new_layer(path): return super().handle_module(path, module)
(self, path: pybind11_stubgen.structs.QualifiedName, module: module) -> pybind11_stubgen.structs.Module | None
707,753
pybind11_stubgen.parser.mixins.fix
OverridePrintSafeValues
null
class OverridePrintSafeValues(IParser): _print_safe_values: re.Pattern | None def __init__(self): super().__init__() self._print_safe_values = None def set_print_safe_value_pattern(self, pattern: re.Pattern): self._print_safe_values = pattern def parse_value_str(self, value: str) -> Value | InvalidExpression: result = super().parse_value_str(value) if ( self._print_safe_values is not None and isinstance(result, Value) and not result.is_print_safe and self._print_safe_values.match(result.repr) is not None ): result.is_print_safe = True return result
()
707,754
pybind11_stubgen.parser.mixins.fix
__init__
null
def __init__(self): super().__init__() self._print_safe_values = None
(self)
707,773
pybind11_stubgen.parser.mixins.fix
parse_value_str
null
def parse_value_str(self, value: str) -> Value | InvalidExpression: result = super().parse_value_str(value) if ( self._print_safe_values is not None and isinstance(result, Value) and not result.is_print_safe and self._print_safe_values.match(result.repr) is not None ): result.is_print_safe = True return result
(self, value: str) -> pybind11_stubgen.structs.Value | pybind11_stubgen.structs.InvalidExpression
707,775
pybind11_stubgen.parser.mixins.fix
set_print_safe_value_pattern
null
def set_print_safe_value_pattern(self, pattern: re.Pattern): self._print_safe_values = pattern
(self, pattern: re.Pattern)
707,776
pybind11_stubgen.parser.mixins.parse
ParserDispatchMixin
null
class ParserDispatchMixin(IParser): def handle_class(self, path: QualifiedName, class_: type) -> Class | None: base_classes = class_.__bases__ result = Class(name=path[-1], bases=self.handle_bases(path, base_classes)) for name, member in inspect.getmembers(class_): obj = self.handle_class_member( QualifiedName([*path, Identifier(name)]), class_, member ) if isinstance(obj, Docstring): result.doc = obj elif isinstance(obj, Alias): result.aliases.append(obj) elif isinstance(obj, Field): result.fields.append(obj) elif isinstance(obj, Class): result.classes.append(obj) elif isinstance(obj, list): # list[Method] result.methods.extend(obj) elif isinstance(obj, Property): result.properties.append(obj) elif obj is None: pass else: raise AssertionError() return result def handle_class_member( self, path: QualifiedName, class_: type, member: Any ) -> Docstring | Alias | Class | list[Method] | Field | Property | None: if inspect.isroutine(member): return self.handle_method(path, member) if self._is_alias(path, member): return self.handle_alias(path, member) if inspect.isclass(member): return self.handle_class(path, member) if self._is_descriptor(member): return self.handle_property(path, member) if path[-1] == "__doc__": return self.handle_docstring(path, member) return self.handle_field(path, member) def handle_module( self, path: QualifiedName, module: types.ModuleType ) -> Module | None: result = Module(name=path[-1]) for name, member in inspect.getmembers(module): obj = self.handle_module_member( QualifiedName([*path, Identifier(name)]), module, member ) if isinstance(obj, Docstring): result.doc = obj elif isinstance(obj, Import): result.imports.add(obj) elif isinstance(obj, Alias): result.aliases.append(obj) elif isinstance(obj, Class): result.classes.append(obj) elif isinstance(obj, list): # list[Function] result.functions.extend(obj) elif isinstance(obj, Module): result.sub_modules.append(obj) elif isinstance(obj, Attribute): result.attributes.append(obj) elif isinstance(obj, TypeVar_): result.type_vars.append(obj) elif obj is None: pass else: raise AssertionError() return result def handle_module_member( self, path: QualifiedName, module: types.ModuleType, member: Any ) -> ( Docstring | Import | Alias | Class | list[Function] | Attribute | Module | None ): member_module = self._get_value_parent_module_name(member) if ( member_module is not None and member_module != module.__name__ or path[-1] == "annotations" ): return self.handle_import(path, member) if self._is_alias(path, member): return self.handle_alias(path, member) if inspect.isroutine(member): return self.handle_function(path, member) if inspect.isclass(member): return self.handle_class(path, member) if inspect.ismodule(member): return self.handle_module(path, member) if path[-1] == "__doc__": return self.handle_docstring(path, member) return self.handle_attribute(path, member) def _get_value_parent_module_name(self, obj: Any) -> str | None: if inspect.ismodule(obj): return obj.__name__.rsplit(".", 1)[0] if inspect.isclass(obj) or inspect.isroutine(obj): return getattr(obj, "__module__", None) return None def _is_alias(self, path: QualifiedName, member: Any): if (inspect.isroutine(member) or inspect.isclass(member)) and path[ -1 ] != member.__name__: return True if inspect.ismodule(member) and member.__name__ != str(path): return True return False def _is_descriptor(self, member: Any) -> bool: # https://docs.python.org/3/glossary.html#term-descriptor # Ignore `__delete__`-only descriptors return hasattr(member, "__get__") or hasattr(member, "__set__")
()
707,777
pybind11_stubgen.parser.mixins.parse
_get_value_parent_module_name
null
def _get_value_parent_module_name(self, obj: Any) -> str | None: if inspect.ismodule(obj): return obj.__name__.rsplit(".", 1)[0] if inspect.isclass(obj) or inspect.isroutine(obj): return getattr(obj, "__module__", None) return None
(self, obj: Any) -> str | None
707,778
pybind11_stubgen.parser.mixins.parse
_is_alias
null
def _is_alias(self, path: QualifiedName, member: Any): if (inspect.isroutine(member) or inspect.isclass(member)) and path[ -1 ] != member.__name__: return True if inspect.ismodule(member) and member.__name__ != str(path): return True return False
(self, path: pybind11_stubgen.structs.QualifiedName, member: Any)
707,779
pybind11_stubgen.parser.mixins.parse
_is_descriptor
null
def _is_descriptor(self, member: Any) -> bool: # https://docs.python.org/3/glossary.html#term-descriptor # Ignore `__delete__`-only descriptors return hasattr(member, "__get__") or hasattr(member, "__set__")
(self, member: Any) -> bool
707,784
pybind11_stubgen.parser.mixins.parse
handle_class
null
def handle_class(self, path: QualifiedName, class_: type) -> Class | None: base_classes = class_.__bases__ result = Class(name=path[-1], bases=self.handle_bases(path, base_classes)) for name, member in inspect.getmembers(class_): obj = self.handle_class_member( QualifiedName([*path, Identifier(name)]), class_, member ) if isinstance(obj, Docstring): result.doc = obj elif isinstance(obj, Alias): result.aliases.append(obj) elif isinstance(obj, Field): result.fields.append(obj) elif isinstance(obj, Class): result.classes.append(obj) elif isinstance(obj, list): # list[Method] result.methods.extend(obj) elif isinstance(obj, Property): result.properties.append(obj) elif obj is None: pass else: raise AssertionError() return result
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type) -> pybind11_stubgen.structs.Class | None
707,785
pybind11_stubgen.parser.mixins.parse
handle_class_member
null
def handle_class_member( self, path: QualifiedName, class_: type, member: Any ) -> Docstring | Alias | Class | list[Method] | Field | Property | None: if inspect.isroutine(member): return self.handle_method(path, member) if self._is_alias(path, member): return self.handle_alias(path, member) if inspect.isclass(member): return self.handle_class(path, member) if self._is_descriptor(member): return self.handle_property(path, member) if path[-1] == "__doc__": return self.handle_docstring(path, member) return self.handle_field(path, member)
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type, member: Any) -> pybind11_stubgen.structs.Docstring | pybind11_stubgen.structs.Alias | pybind11_stubgen.structs.Class | list[pybind11_stubgen.structs.Method] | pybind11_stubgen.structs.Field | pybind11_stubgen.structs.Property | None
707,791
pybind11_stubgen.parser.mixins.parse
handle_module
null
def handle_module( self, path: QualifiedName, module: types.ModuleType ) -> Module | None: result = Module(name=path[-1]) for name, member in inspect.getmembers(module): obj = self.handle_module_member( QualifiedName([*path, Identifier(name)]), module, member ) if isinstance(obj, Docstring): result.doc = obj elif isinstance(obj, Import): result.imports.add(obj) elif isinstance(obj, Alias): result.aliases.append(obj) elif isinstance(obj, Class): result.classes.append(obj) elif isinstance(obj, list): # list[Function] result.functions.extend(obj) elif isinstance(obj, Module): result.sub_modules.append(obj) elif isinstance(obj, Attribute): result.attributes.append(obj) elif isinstance(obj, TypeVar_): result.type_vars.append(obj) elif obj is None: pass else: raise AssertionError() return result
(self, path: pybind11_stubgen.structs.QualifiedName, module: module) -> pybind11_stubgen.structs.Module | None
707,792
pybind11_stubgen.parser.mixins.parse
handle_module_member
null
def handle_module_member( self, path: QualifiedName, module: types.ModuleType, member: Any ) -> ( Docstring | Import | Alias | Class | list[Function] | Attribute | Module | None ): member_module = self._get_value_parent_module_name(member) if ( member_module is not None and member_module != module.__name__ or path[-1] == "annotations" ): return self.handle_import(path, member) if self._is_alias(path, member): return self.handle_alias(path, member) if inspect.isroutine(member): return self.handle_function(path, member) if inspect.isclass(member): return self.handle_class(path, member) if inspect.ismodule(member): return self.handle_module(path, member) if path[-1] == "__doc__": return self.handle_docstring(path, member) return self.handle_attribute(path, member)
(self, path: pybind11_stubgen.structs.QualifiedName, module: module, member: Any) -> pybind11_stubgen.structs.Docstring | pybind11_stubgen.structs.Import | pybind11_stubgen.structs.Alias | pybind11_stubgen.structs.Class | list[pybind11_stubgen.structs.Function] | pybind11_stubgen.structs.Attribute | pybind11_stubgen.structs.Module | None
707,867
pybind11_stubgen.printer
Printer
null
class Printer: def __init__(self, invalid_expr_as_ellipses: bool): self.invalid_expr_as_ellipses = invalid_expr_as_ellipses def print_alias(self, alias: Alias) -> list[str]: return [f"{alias.name} = {alias.origin}"] def print_attribute(self, attr: Attribute) -> list[str]: parts = [ f"{attr.name}", ] if attr.annotation is not None: parts.append(f": {self.print_annotation(attr.annotation)}") if attr.value is not None and attr.value.is_print_safe: parts.append(f" = {self.print_value(attr.value)}") else: if attr.annotation is None: parts.append(" = ...") if attr.value is not None: parts.append(f" # value = {self.print_value(attr.value)}") return ["".join(parts)] def print_argument(self, arg: Argument) -> str: parts = [] if arg.variadic: parts += ["*"] if arg.kw_variadic: parts += ["**"] parts.append(f"{arg.name}") if arg.annotation is not None: parts.append(f": {self.print_annotation(arg.annotation)}") if isinstance(arg.default, Value): if arg.default.is_print_safe: parts.append(f" = {self.print_value(arg.default)}") else: parts.append(" = ...") elif isinstance(arg.default, InvalidExpression): parts.append(f" = {self.print_invalid_exp(arg.default)}") return "".join(parts) def print_class(self, class_: Class) -> list[str]: if class_.bases: base_list = "(" + ", ".join(str(base) for base in class_.bases) + ")" else: base_list = "" return [ f"class {class_.name}{base_list}:", *indent_lines(self.print_class_body(class_)), ] def print_type_var(self, type_var: TypeVar_) -> list[str]: return [str(type_var)] def print_class_body(self, class_: Class) -> list[str]: result = [] if class_.doc is not None: result.extend(self.print_docstring(class_.doc)) for sub_class in sorted(class_.classes, key=lambda c: c.name): result.extend(self.print_class(sub_class)) modifier_order: dict[Modifier, int] = { "static": 0, "class": 1, None: 2, } for field in sorted( class_.fields, key=lambda f: (modifier_order[f.modifier], f.attribute.name) ): result.extend(self.print_field(field)) for alias in sorted(class_.aliases, key=lambda a: a.name): result.extend(self.print_alias(alias)) for method in sorted( class_.methods, key=lambda m: (modifier_order[m.modifier], m.function.name) ): result.extend(self.print_method(method)) for prop in sorted(class_.properties, key=lambda p: p.name): result.extend(self.print_property(prop)) if not result: result = ["pass"] return result def print_docstring(self, doc: Docstring) -> list[str]: return [ '"""', *( line.replace("\\", r"\\").replace('"""', r"\"\"\"") for line in doc.splitlines() ), '"""', ] def print_field(self, field: Field) -> list[str]: return self.print_attribute(field.attribute) # FIXME: modifier def print_function(self, func: Function) -> list[str]: pos_only = False kw_only = False args = [] for arg in func.args: if arg.variadic: pos_only = True kw_only = True if not pos_only and not arg.pos_only: pos_only = True if sys.version_info >= (3, 8): args.append("/") if not kw_only and arg.kw_only: kw_only = True args.append("*") args.append(self.print_argument(arg)) if len(args) > 0 and args[0] == "/": args = args[1:] signature = [ f"def {func.name}(", ", ".join(args), ")", ] if func.returns is not None: signature.append(f" -> {self.print_annotation(func.returns)}") signature.append(":") result: list[str] = [ *(f"@{decorator}" for decorator in func.decorators), "".join(signature), ] if func.doc is not None: body = self.print_docstring(func.doc) else: body = ["..."] result.extend(indent_lines(body)) return result def print_submodule_import(self, name: Identifier) -> list[str]: return [f"from . import {name}"] def print_import(self, import_: Import) -> list[str]: parent = str(import_.origin.parent) if import_.name is None: return [f"import {import_.origin}"] if len(parent) == 0: return [f"import {import_.origin} as {import_.name}"] result = f"from {parent} import {import_.origin[-1]}" if import_.name != import_.origin[-1]: result += f" as {import_.name}" return [result] def print_method(self, method: Method) -> list[str]: result = [] if method.modifier == "static": result += ["@staticmethod"] elif method.modifier == "class": result += ["@classmethod"] elif method.modifier is None: pass else: raise RuntimeError() result.extend(self.print_function(method.function)) return result def print_module(self, module: Module) -> list[str]: result = [] if module.doc is not None: result.extend(self.print_docstring(module.doc)) for import_ in sorted(module.imports, key=lambda x: x.origin): result.extend(self.print_import(import_)) for sub_module in module.sub_modules: result.extend(self.print_submodule_import(sub_module.name)) # Place __all__ above everything for attr in sorted(module.attributes, key=lambda a: a.name): if attr.name == "__all__": result.extend(self.print_attribute(attr)) break for type_var in sorted(module.type_vars, key=lambda t: t.name): result.extend(self.print_type_var(type_var)) for class_ in sorted(module.classes, key=lambda c: c.name): result.extend(self.print_class(class_)) for func in sorted(module.functions, key=lambda f: f.name): result.extend(self.print_function(func)) for attr in sorted(module.attributes, key=lambda a: a.name): if attr.name != "__all__": result.extend(self.print_attribute(attr)) for alias in module.aliases: result.extend(self.print_alias(alias)) return result def print_property(self, prop: Property) -> list[str]: if not prop.getter: # FIXME: support setter-only props return [] # FIXME: add modifier result = [] result.extend( [ "@property", *self.print_function( dataclasses.replace( prop.getter, name=prop.name, # replace getter docstring if prop.doc exists doc=prop.doc if prop.doc is not None else prop.getter.doc, ) ), ] ) if prop.setter: result.extend( [ f"@{prop.name}.setter", *self.print_function( dataclasses.replace( prop.setter, name=prop.name, # remove setter docstring if prop.doc exists doc=None if prop.doc is not None else prop.setter.doc, ) ), ] ) return result def print_value(self, value: Value) -> str: split = value.repr.split("\n", 1) if len(split) == 1: return split[0] else: return split[0] + "..." def print_type(self, type_: ResolvedType) -> str: if ( str(type_.name) == "typing.Optional" and type_.parameters is not None and len(type_.parameters) == 1 ): return f"{self.print_annotation(type_.parameters[0])} | None" if str(type_.name) == "typing.Union" and type_.parameters is not None: return " | ".join(self.print_annotation(p) for p in type_.parameters) if type_.parameters: param_str = ( "[" + ", ".join(self.print_annotation(p) for p in type_.parameters) + "]" ) else: param_str = "" return f"{type_.name}{param_str}" def print_annotation(self, annotation: Annotation) -> str: if isinstance(annotation, ResolvedType): return self.print_type(annotation) elif isinstance(annotation, Value): return self.print_value(annotation) elif isinstance(annotation, InvalidExpression): return self.print_invalid_exp(annotation) else: raise AssertionError() def print_invalid_exp(self, invalid_expr: InvalidExpression) -> str: if self.invalid_expr_as_ellipses: return "..." return invalid_expr.text
(invalid_expr_as_ellipses: 'bool')
707,868
pybind11_stubgen.printer
__init__
null
def __init__(self, invalid_expr_as_ellipses: bool): self.invalid_expr_as_ellipses = invalid_expr_as_ellipses
(self, invalid_expr_as_ellipses: bool)
707,869
pybind11_stubgen.printer
print_alias
null
def print_alias(self, alias: Alias) -> list[str]: return [f"{alias.name} = {alias.origin}"]
(self, alias: pybind11_stubgen.structs.Alias) -> list[str]
707,870
pybind11_stubgen.printer
print_annotation
null
def print_annotation(self, annotation: Annotation) -> str: if isinstance(annotation, ResolvedType): return self.print_type(annotation) elif isinstance(annotation, Value): return self.print_value(annotation) elif isinstance(annotation, InvalidExpression): return self.print_invalid_exp(annotation) else: raise AssertionError()
(self, annotation: Union[pybind11_stubgen.structs.ResolvedType, pybind11_stubgen.structs.Value, pybind11_stubgen.structs.InvalidExpression]) -> str
707,871
pybind11_stubgen.printer
print_argument
null
def print_argument(self, arg: Argument) -> str: parts = [] if arg.variadic: parts += ["*"] if arg.kw_variadic: parts += ["**"] parts.append(f"{arg.name}") if arg.annotation is not None: parts.append(f": {self.print_annotation(arg.annotation)}") if isinstance(arg.default, Value): if arg.default.is_print_safe: parts.append(f" = {self.print_value(arg.default)}") else: parts.append(" = ...") elif isinstance(arg.default, InvalidExpression): parts.append(f" = {self.print_invalid_exp(arg.default)}") return "".join(parts)
(self, arg: pybind11_stubgen.structs.Argument) -> str
707,872
pybind11_stubgen.printer
print_attribute
null
def print_attribute(self, attr: Attribute) -> list[str]: parts = [ f"{attr.name}", ] if attr.annotation is not None: parts.append(f": {self.print_annotation(attr.annotation)}") if attr.value is not None and attr.value.is_print_safe: parts.append(f" = {self.print_value(attr.value)}") else: if attr.annotation is None: parts.append(" = ...") if attr.value is not None: parts.append(f" # value = {self.print_value(attr.value)}") return ["".join(parts)]
(self, attr: pybind11_stubgen.structs.Attribute) -> list[str]
707,873
pybind11_stubgen.printer
print_class
null
def print_class(self, class_: Class) -> list[str]: if class_.bases: base_list = "(" + ", ".join(str(base) for base in class_.bases) + ")" else: base_list = "" return [ f"class {class_.name}{base_list}:", *indent_lines(self.print_class_body(class_)), ]
(self, class_: pybind11_stubgen.structs.Class) -> list[str]
707,874
pybind11_stubgen.printer
print_class_body
null
def print_class_body(self, class_: Class) -> list[str]: result = [] if class_.doc is not None: result.extend(self.print_docstring(class_.doc)) for sub_class in sorted(class_.classes, key=lambda c: c.name): result.extend(self.print_class(sub_class)) modifier_order: dict[Modifier, int] = { "static": 0, "class": 1, None: 2, } for field in sorted( class_.fields, key=lambda f: (modifier_order[f.modifier], f.attribute.name) ): result.extend(self.print_field(field)) for alias in sorted(class_.aliases, key=lambda a: a.name): result.extend(self.print_alias(alias)) for method in sorted( class_.methods, key=lambda m: (modifier_order[m.modifier], m.function.name) ): result.extend(self.print_method(method)) for prop in sorted(class_.properties, key=lambda p: p.name): result.extend(self.print_property(prop)) if not result: result = ["pass"] return result
(self, class_: pybind11_stubgen.structs.Class) -> list[str]
707,875
pybind11_stubgen.printer
print_docstring
null
def print_docstring(self, doc: Docstring) -> list[str]: return [ '"""', *( line.replace("\\", r"\\").replace('"""', r"\"\"\"") for line in doc.splitlines() ), '"""', ]
(self, doc: pybind11_stubgen.structs.Docstring) -> list[str]
707,876
pybind11_stubgen.printer
print_field
null
def print_field(self, field: Field) -> list[str]: return self.print_attribute(field.attribute) # FIXME: modifier
(self, field: pybind11_stubgen.structs.Field) -> list[str]
707,877
pybind11_stubgen.printer
print_function
null
def print_function(self, func: Function) -> list[str]: pos_only = False kw_only = False args = [] for arg in func.args: if arg.variadic: pos_only = True kw_only = True if not pos_only and not arg.pos_only: pos_only = True if sys.version_info >= (3, 8): args.append("/") if not kw_only and arg.kw_only: kw_only = True args.append("*") args.append(self.print_argument(arg)) if len(args) > 0 and args[0] == "/": args = args[1:] signature = [ f"def {func.name}(", ", ".join(args), ")", ] if func.returns is not None: signature.append(f" -> {self.print_annotation(func.returns)}") signature.append(":") result: list[str] = [ *(f"@{decorator}" for decorator in func.decorators), "".join(signature), ] if func.doc is not None: body = self.print_docstring(func.doc) else: body = ["..."] result.extend(indent_lines(body)) return result
(self, func: pybind11_stubgen.structs.Function) -> list[str]
707,878
pybind11_stubgen.printer
print_import
null
def print_import(self, import_: Import) -> list[str]: parent = str(import_.origin.parent) if import_.name is None: return [f"import {import_.origin}"] if len(parent) == 0: return [f"import {import_.origin} as {import_.name}"] result = f"from {parent} import {import_.origin[-1]}" if import_.name != import_.origin[-1]: result += f" as {import_.name}" return [result]
(self, import_: pybind11_stubgen.structs.Import) -> list[str]
707,879
pybind11_stubgen.printer
print_invalid_exp
null
def print_invalid_exp(self, invalid_expr: InvalidExpression) -> str: if self.invalid_expr_as_ellipses: return "..." return invalid_expr.text
(self, invalid_expr: pybind11_stubgen.structs.InvalidExpression) -> str
707,880
pybind11_stubgen.printer
print_method
null
def print_method(self, method: Method) -> list[str]: result = [] if method.modifier == "static": result += ["@staticmethod"] elif method.modifier == "class": result += ["@classmethod"] elif method.modifier is None: pass else: raise RuntimeError() result.extend(self.print_function(method.function)) return result
(self, method: pybind11_stubgen.structs.Method) -> list[str]
707,881
pybind11_stubgen.printer
print_module
null
def print_module(self, module: Module) -> list[str]: result = [] if module.doc is not None: result.extend(self.print_docstring(module.doc)) for import_ in sorted(module.imports, key=lambda x: x.origin): result.extend(self.print_import(import_)) for sub_module in module.sub_modules: result.extend(self.print_submodule_import(sub_module.name)) # Place __all__ above everything for attr in sorted(module.attributes, key=lambda a: a.name): if attr.name == "__all__": result.extend(self.print_attribute(attr)) break for type_var in sorted(module.type_vars, key=lambda t: t.name): result.extend(self.print_type_var(type_var)) for class_ in sorted(module.classes, key=lambda c: c.name): result.extend(self.print_class(class_)) for func in sorted(module.functions, key=lambda f: f.name): result.extend(self.print_function(func)) for attr in sorted(module.attributes, key=lambda a: a.name): if attr.name != "__all__": result.extend(self.print_attribute(attr)) for alias in module.aliases: result.extend(self.print_alias(alias)) return result
(self, module: pybind11_stubgen.structs.Module) -> list[str]
707,882
pybind11_stubgen.printer
print_property
null
def print_property(self, prop: Property) -> list[str]: if not prop.getter: # FIXME: support setter-only props return [] # FIXME: add modifier result = [] result.extend( [ "@property", *self.print_function( dataclasses.replace( prop.getter, name=prop.name, # replace getter docstring if prop.doc exists doc=prop.doc if prop.doc is not None else prop.getter.doc, ) ), ] ) if prop.setter: result.extend( [ f"@{prop.name}.setter", *self.print_function( dataclasses.replace( prop.setter, name=prop.name, # remove setter docstring if prop.doc exists doc=None if prop.doc is not None else prop.setter.doc, ) ), ] ) return result
(self, prop: pybind11_stubgen.structs.Property) -> list[str]
707,883
pybind11_stubgen.printer
print_submodule_import
null
def print_submodule_import(self, name: Identifier) -> list[str]: return [f"from . import {name}"]
(self, name: pybind11_stubgen.structs.Identifier) -> list[str]
707,884
pybind11_stubgen.printer
print_type
null
def print_type(self, type_: ResolvedType) -> str: if ( str(type_.name) == "typing.Optional" and type_.parameters is not None and len(type_.parameters) == 1 ): return f"{self.print_annotation(type_.parameters[0])} | None" if str(type_.name) == "typing.Union" and type_.parameters is not None: return " | ".join(self.print_annotation(p) for p in type_.parameters) if type_.parameters: param_str = ( "[" + ", ".join(self.print_annotation(p) for p in type_.parameters) + "]" ) else: param_str = "" return f"{type_.name}{param_str}"
(self, type_: pybind11_stubgen.structs.ResolvedType) -> str
707,885
pybind11_stubgen.printer
print_type_var
null
def print_type_var(self, type_var: TypeVar_) -> list[str]: return [str(type_var)]
(self, type_var: pybind11_stubgen.structs.TypeVar_) -> list[str]
707,886
pybind11_stubgen.printer
print_value
null
def print_value(self, value: Value) -> str: split = value.repr.split("\n", 1) if len(split) == 1: return split[0] else: return split[0] + "..."
(self, value: pybind11_stubgen.structs.Value) -> str
707,887
pybind11_stubgen.structs
QualifiedName
Fully Qualified Name
class QualifiedName(Tuple[Identifier, ...]): """Fully Qualified Name""" @classmethod def from_str(cls, name: str) -> QualifiedName: return QualifiedName(Identifier(part) for part in name.split(".")) def __str__(self): return ".".join(self) @property def parent(self) -> QualifiedName: return QualifiedName(self[:-1])
(iterable=(), /)
707,888
pybind11_stubgen.structs
__str__
null
def __str__(self): return ".".join(self)
(self)
707,889
pybind11_stubgen.parser.mixins.fix
RemoveSelfAnnotation
null
class RemoveSelfAnnotation(IParser): __any_t_name = QualifiedName.from_str("Any") __typing_any_t_name = QualifiedName.from_str("typing.Any") def handle_method(self, path: QualifiedName, method: Any) -> list[Method]: methods = super().handle_method(path, method) for method in methods: self._remove_self_arg_annotation(path, method.function) return methods def handle_property(self, path: QualifiedName, prop: Any) -> Property | None: prop = super().handle_property(path, prop) if prop is not None: if prop.getter is not None: self._remove_self_arg_annotation(path, prop.getter) if prop.setter is not None: self._remove_self_arg_annotation(path, prop.setter) return prop def _remove_self_arg_annotation(self, path: QualifiedName, func: Function) -> None: if len(func.args) == 0: return fully_qualified_class_name = QualifiedName(path[:-1]) # remove the method name first_arg = func.args[0] if ( first_arg.name == "self" and isinstance(first_arg.annotation, ResolvedType) and not first_arg.annotation.parameters and ( first_arg.annotation.name in { self.__any_t_name, self.__typing_any_t_name, fully_qualified_class_name, fully_qualified_class_name[-len(first_arg.annotation.name) :], } ) ): first_arg.annotation = None
()
707,890
pybind11_stubgen.parser.mixins.fix
_remove_self_arg_annotation
null
def _remove_self_arg_annotation(self, path: QualifiedName, func: Function) -> None: if len(func.args) == 0: return fully_qualified_class_name = QualifiedName(path[:-1]) # remove the method name first_arg = func.args[0] if ( first_arg.name == "self" and isinstance(first_arg.annotation, ResolvedType) and not first_arg.annotation.parameters and ( first_arg.annotation.name in { self.__any_t_name, self.__typing_any_t_name, fully_qualified_class_name, fully_qualified_class_name[-len(first_arg.annotation.name) :], } ) ): first_arg.annotation = None
(self, path: pybind11_stubgen.structs.QualifiedName, func: pybind11_stubgen.structs.Function) -> NoneType
707,901
pybind11_stubgen.parser.mixins.fix
handle_method
null
def handle_method(self, path: QualifiedName, method: Any) -> list[Method]: methods = super().handle_method(path, method) for method in methods: self._remove_self_arg_annotation(path, method.function) return methods
(self, path: pybind11_stubgen.structs.QualifiedName, method: Any) -> list[pybind11_stubgen.structs.Method]
707,904
pybind11_stubgen.parser.mixins.fix
handle_property
null
def handle_property(self, path: QualifiedName, prop: Any) -> Property | None: prop = super().handle_property(path, prop) if prop is not None: if prop.getter is not None: self._remove_self_arg_annotation(path, prop.getter) if prop.setter is not None: self._remove_self_arg_annotation(path, prop.setter) return prop
(self, path: pybind11_stubgen.structs.QualifiedName, prop: Any) -> pybind11_stubgen.structs.Property | None
707,911
pybind11_stubgen.parser.mixins.fix
ReplaceReadWritePropertyWithField
null
class ReplaceReadWritePropertyWithField(IParser): def handle_class_member( self, path: QualifiedName, class_: type, obj: Any ) -> Docstring | Alias | Class | list[Method] | Field | Property | None: result = super().handle_class_member(path, class_, obj) if isinstance(result, Property): if ( result.doc is None and result.getter is not None and result.setter is not None and len(result.getter.args) == 1 and len(result.setter.args) == 2 and result.getter.doc is None and result.setter.doc is None and result.getter.returns == result.setter.args[1].annotation ): return Field( attribute=Attribute( name=result.name, annotation=result.getter.returns, value=None ), modifier=None, ) return result
()
707,917
pybind11_stubgen.parser.mixins.fix
handle_class_member
null
def handle_class_member( self, path: QualifiedName, class_: type, obj: Any ) -> Docstring | Alias | Class | list[Method] | Field | Property | None: result = super().handle_class_member(path, class_, obj) if isinstance(result, Property): if ( result.doc is None and result.getter is not None and result.setter is not None and len(result.getter.args) == 1 and len(result.setter.args) == 2 and result.getter.doc is None and result.setter.doc is None and result.getter.returns == result.setter.args[1].annotation ): return Field( attribute=Attribute( name=result.name, annotation=result.getter.returns, value=None ), modifier=None, ) return result
(self, path: pybind11_stubgen.structs.QualifiedName, class_: type, obj: Any) -> pybind11_stubgen.structs.Docstring | pybind11_stubgen.structs.Alias | pybind11_stubgen.structs.Class | list[pybind11_stubgen.structs.Method] | pybind11_stubgen.structs.Field | pybind11_stubgen.structs.Property | None
707,932
pybind11_stubgen.parser.mixins.fix
RewritePybind11EnumValueRepr
null
class RewritePybind11EnumValueRepr(IParser): _pybind11_enum_pattern = re.compile(r"<(?P<enum>\w+(\.\w+)+): (?P<value>-?\d+)>") # _pybind11_enum_pattern = re.compile(r"<(?P<enum>\w+(\.\w+)+): (?P<value>\d+)>") _unknown_enum_classes: set[str] = set() def __init__(self): super().__init__() self._pybind11_enum_locations: dict[re.Pattern, str] = {} def set_pybind11_enum_locations(self, locations: dict[re.Pattern, str]): self._pybind11_enum_locations = locations def parse_value_str(self, value: str) -> Value | InvalidExpression: value = value.strip() match = self._pybind11_enum_pattern.match(value) if match is not None: enum_qual_name = match.group("enum") enum_class_str, entry = enum_qual_name.rsplit(".", maxsplit=1) for pattern, prefix in self._pybind11_enum_locations.items(): if pattern.match(enum_class_str) is None: continue enum_class = self.parse_annotation_str(f"{prefix}.{enum_class_str}") if isinstance(enum_class, ResolvedType): return Value(repr=f"{enum_class.name}.{entry}", is_print_safe=True) return super().parse_value_str(value) def report_error(self, error: ParserError) -> None: if isinstance(error, InvalidExpressionError): match = self._pybind11_enum_pattern.match(error.expression) if match is not None: enum_qual_name = match.group("enum") enum_class_str, entry = enum_qual_name.rsplit(".", maxsplit=1) self._unknown_enum_classes.add(enum_class_str) super().report_error(error) def finalize(self): if self._unknown_enum_classes: logger.warning( "Enum-like str representations were found with no " "matching mapping to the enum class location.\n" "Use `--enum-class-locations` to specify " "full path to the following enum(s):\n" + "\n".join(f" - {c}" for c in self._unknown_enum_classes) ) super().finalize()
()
707,933
pybind11_stubgen.parser.mixins.fix
__init__
null
def __init__(self): super().__init__() self._pybind11_enum_locations: dict[re.Pattern, str] = {}
(self)
707,934
pybind11_stubgen.parser.mixins.fix
finalize
null
def finalize(self): if self._unknown_enum_classes: logger.warning( "Enum-like str representations were found with no " "matching mapping to the enum class location.\n" "Use `--enum-class-locations` to specify " "full path to the following enum(s):\n" + "\n".join(f" - {c}" for c in self._unknown_enum_classes) ) super().finalize()
(self)
707,952
pybind11_stubgen.parser.mixins.fix
parse_value_str
null
def parse_value_str(self, value: str) -> Value | InvalidExpression: value = value.strip() match = self._pybind11_enum_pattern.match(value) if match is not None: enum_qual_name = match.group("enum") enum_class_str, entry = enum_qual_name.rsplit(".", maxsplit=1) for pattern, prefix in self._pybind11_enum_locations.items(): if pattern.match(enum_class_str) is None: continue enum_class = self.parse_annotation_str(f"{prefix}.{enum_class_str}") if isinstance(enum_class, ResolvedType): return Value(repr=f"{enum_class.name}.{entry}", is_print_safe=True) return super().parse_value_str(value)
(self, value: str) -> pybind11_stubgen.structs.Value | pybind11_stubgen.structs.InvalidExpression
707,953
pybind11_stubgen.parser.mixins.fix
report_error
null
def report_error(self, error: ParserError) -> None: if isinstance(error, InvalidExpressionError): match = self._pybind11_enum_pattern.match(error.expression) if match is not None: enum_qual_name = match.group("enum") enum_class_str, entry = enum_qual_name.rsplit(".", maxsplit=1) self._unknown_enum_classes.add(enum_class_str) super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError) -> NoneType
707,954
pybind11_stubgen.parser.mixins.fix
set_pybind11_enum_locations
null
def set_pybind11_enum_locations(self, locations: dict[re.Pattern, str]): self._pybind11_enum_locations = locations
(self, locations: dict[re.Pattern, str])
707,955
pybind11_stubgen.parser.mixins.error_handlers
SuggestCxxSignatureFix
null
class SuggestCxxSignatureFix(IParser): def __init__(self): super().__init__() self.suggest_cxx_fix = False def report_error(self, error: ParserError): if isinstance(error, InvalidExpressionError): expression = error.expression if "::" in expression or expression.endswith(">"): self.suggest_cxx_fix = True super().report_error(error) def finalize(self): if self.suggest_cxx_fix: logger.warning( "Raw C++ types/values were found in signatures extracted " "from docstrings.\n" "Please check the corresponding sections of pybind11 documentation " "to avoid common mistakes in binding code:\n" " - https://pybind11.readthedocs.io/en/latest/advanced/misc.html" "#avoiding-cpp-types-in-docstrings\n" " - https://pybind11.readthedocs.io/en/latest/advanced/functions.html" "#default-arguments-revisited" ) super().finalize()
()
707,956
pybind11_stubgen.parser.mixins.error_handlers
__init__
null
def __init__(self): super().__init__() self.suggest_cxx_fix = False
(self)
707,957
pybind11_stubgen.parser.mixins.error_handlers
finalize
null
def finalize(self): if self.suggest_cxx_fix: logger.warning( "Raw C++ types/values were found in signatures extracted " "from docstrings.\n" "Please check the corresponding sections of pybind11 documentation " "to avoid common mistakes in binding code:\n" " - https://pybind11.readthedocs.io/en/latest/advanced/misc.html" "#avoiding-cpp-types-in-docstrings\n" " - https://pybind11.readthedocs.io/en/latest/advanced/functions.html" "#default-arguments-revisited" ) super().finalize()
(self)
707,976
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): if isinstance(error, InvalidExpressionError): expression = error.expression if "::" in expression or expression.endswith(">"): self.suggest_cxx_fix = True super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,977
pybind11_stubgen.parser.mixins.error_handlers
TerminateOnFatalErrors
null
class TerminateOnFatalErrors(IParser): def __init__(self): super().__init__() self.__found_fatal_errors = False def report_error(self, error: ParserError): self.__found_fatal_errors = True super().report_error(error) def finalize(self): super().finalize() if self.__found_fatal_errors: logger.info("Terminating due to previous errors") sys.exit(1)
()
707,978
pybind11_stubgen.parser.mixins.error_handlers
__init__
null
def __init__(self): super().__init__() self.__found_fatal_errors = False
(self)
707,979
pybind11_stubgen.parser.mixins.error_handlers
finalize
null
def finalize(self): super().finalize() if self.__found_fatal_errors: logger.info("Terminating due to previous errors") sys.exit(1)
(self)
707,998
pybind11_stubgen.parser.mixins.error_handlers
report_error
null
def report_error(self, error: ParserError): self.__found_fatal_errors = True super().report_error(error)
(self, error: pybind11_stubgen.parser.errors.ParserError)
707,999
pybind11_stubgen.writer
Writer
null
class Writer: def __init__(self, stub_ext: str = "pyi"): # assert stub_extension in ["pyi", "py"] self.stub_ext: str = stub_ext def write_module( self, module: Module, printer: Printer, to: Path, sub_dir: Path | None = None ): assert to.exists() assert to.is_dir() if module.sub_modules or sub_dir is not None: if sub_dir is None: sub_dir = Path(module.name) module_dir = to / sub_dir module_dir.mkdir(exist_ok=True) module_file = module_dir / f"__init__.{self.stub_ext}" else: module_file = to / f"{module.name}.{self.stub_ext}" with open(module_file, "w", encoding="utf-8") as f: f.writelines(line + "\n" for line in printer.print_module(module)) for sub_module in module.sub_modules: self.write_module(sub_module, printer, to=module_dir)
(stub_ext: 'str' = 'pyi')
708,000
pybind11_stubgen.writer
__init__
null
def __init__(self, stub_ext: str = "pyi"): # assert stub_extension in ["pyi", "py"] self.stub_ext: str = stub_ext
(self, stub_ext: str = 'pyi')
708,001
pybind11_stubgen.writer
write_module
null
def write_module( self, module: Module, printer: Printer, to: Path, sub_dir: Path | None = None ): assert to.exists() assert to.is_dir() if module.sub_modules or sub_dir is not None: if sub_dir is None: sub_dir = Path(module.name) module_dir = to / sub_dir module_dir.mkdir(exist_ok=True) module_file = module_dir / f"__init__.{self.stub_ext}" else: module_file = to / f"{module.name}.{self.stub_ext}" with open(module_file, "w", encoding="utf-8") as f: f.writelines(line + "\n" for line in printer.print_module(module)) for sub_module in module.sub_modules: self.write_module(sub_module, printer, to=module_dir)
(self, module: pybind11_stubgen.structs.Module, printer: pybind11_stubgen.printer.Printer, to: pathlib.Path, sub_dir: Optional[pathlib.Path] = None)
708,002
pybind11_stubgen
arg_parser
null
def arg_parser() -> ArgumentParser: def regex(pattern_str: str) -> re.Pattern: try: return re.compile(pattern_str) except re.error as e: raise ValueError(f"Invalid REGEX pattern: {e}") def regex_colon_path(regex_path: str) -> tuple[re.Pattern, str]: pattern_str, path = regex_path.rsplit(":", maxsplit=1) if any(not part.isidentifier() for part in path.split(".")): raise ValueError(f"Invalid PATH: {path}") return regex(pattern_str), path parser = ArgumentParser( prog="pybind11-stubgen", description="Generates stubs for specified modules" ) parser.add_argument( "-o", "--output-dir", help="The root directory for output stubs", default="./stubs", ) parser.add_argument( "--root-suffix", type=str, default=None, dest="root_suffix", help="Top-level module directory suffix", ) parser.add_argument( "--ignore-invalid-expressions", metavar="REGEX", default=None, type=regex, help="Ignore invalid expressions matching REGEX", ) parser.add_argument( "--ignore-invalid-identifiers", metavar="REGEX", default=None, type=regex, help="Ignore invalid identifiers matching REGEX", ) parser.add_argument( "--ignore-unresolved-names", metavar="REGEX", default=None, type=regex, help="Ignore unresolved names matching REGEX", ) parser.add_argument( "--ignore-all-errors", default=False, action="store_true", help="Ignore all errors during module parsing", ) parser.add_argument( "--enum-class-locations", dest="enum_class_locations", metavar="REGEX:LOC", action="append", default=[], type=regex_colon_path, help="Locations of enum classes in " "<enum-class-name-regex>:<path-to-class> format. " "Example: `MyEnum:foo.bar.Baz`", ) numpy_array_fix = parser.add_mutually_exclusive_group() numpy_array_fix.add_argument( "--numpy-array-wrap-with-annotated", default=False, action="store_true", help="Replace numpy/scipy arrays of " "'ARRAY_T[TYPE, [*DIMS], *FLAGS]' format with " "'Annotated[ARRAY_T, TYPE, FixedSize|DynamicSize(*DIMS), *FLAGS]'", ) numpy_array_fix.add_argument( "--numpy-array-use-type-var", default=False, action="store_true", help="Replace 'numpy.ndarray[numpy.float32[m, 1]]' with " "'numpy.ndarray[tuple[M, typing.Literal[1]], numpy.dtype[numpy.float32]]'", ) numpy_array_fix.add_argument( "--numpy-array-remove-parameters", default=False, action="store_true", help="Replace 'numpy.ndarray[...]' with 'numpy.ndarray'", ) parser.add_argument( "--print-invalid-expressions-as-is", default=False, action="store_true", help="Suppress the replacement with '...' of invalid expressions" "found in annotations", ) parser.add_argument( "--print-safe-value-reprs", metavar="REGEX", default=None, type=regex, help="Override the print-safe check for values matching REGEX", ) parser.add_argument( "--exit-code", action="store_true", dest="exit_code", help="On error exits with 1 and skips stub generation", ) parser.add_argument( "--dry-run", action="store_true", dest="dry_run", help="Don't write stubs. Parses module and report errors", ) parser.add_argument( "--stub-extension", type=str, default="pyi", metavar="EXT", choices=["pyi", "py"], help="The file extension of the generated stubs. " "Must be 'pyi' (default) or 'py'", ) parser.add_argument( "module_name", metavar="MODULE_NAME", type=str, help="module name", ) return parser
() -> argparse.ArgumentParser
708,005
pybind11_stubgen
main
null
def main(): logging.basicConfig( level=logging.INFO, format="%(name)s - [%(levelname)7s] %(message)s", ) args = arg_parser().parse_args(namespace=CLIArgs()) parser = stub_parser_from_args(args) printer = Printer(invalid_expr_as_ellipses=not args.print_invalid_expressions_as_is) out_dir, sub_dir = to_output_and_subdir( output_dir=args.output_dir, module_name=args.module_name, root_suffix=args.root_suffix, ) run( parser, printer, args.module_name, out_dir, sub_dir=sub_dir, dry_run=args.dry_run, writer=Writer(stub_ext=args.stub_extension), )
()
708,009
pybind11_stubgen
run
null
def run( parser: IParser, printer: Printer, module_name: str, out_dir: Path, sub_dir: Path | None, dry_run: bool, writer: Writer, ): module = parser.handle_module( QualifiedName.from_str(module_name), importlib.import_module(module_name) ) parser.finalize() if module is None: raise RuntimeError(f"Can't parse {module_name}") if dry_run: return out_dir.mkdir(exist_ok=True, parents=True) writer.write_module(module, printer, to=out_dir, sub_dir=sub_dir)
(parser: pybind11_stubgen.parser.interface.IParser, printer: pybind11_stubgen.printer.Printer, module_name: str, out_dir: pathlib.Path, sub_dir: pathlib.Path | None, dry_run: bool, writer: pybind11_stubgen.writer.Writer)
708,011
pybind11_stubgen
stub_parser_from_args
null
def stub_parser_from_args(args: CLIArgs) -> IParser: error_handlers_top: list[type] = [ LoggerData, *([IgnoreAllErrors] if args.ignore_all_errors else []), *([IgnoreInvalidIdentifierErrors] if args.ignore_invalid_identifiers else []), *([IgnoreInvalidExpressionErrors] if args.ignore_invalid_expressions else []), *([IgnoreUnresolvedNameErrors] if args.ignore_unresolved_names else []), ] error_handlers_bottom: list[type] = [ LogErrors, SuggestCxxSignatureFix, *([TerminateOnFatalErrors] if args.exit_code else []), ] numpy_fixes: list[type] = [ *([FixNumpyArrayDimAnnotation] if args.numpy_array_wrap_with_annotated else []), *([FixNumpyArrayDimTypeVar] if args.numpy_array_use_type_var else []), *( [FixNumpyArrayRemoveParameters] if args.numpy_array_remove_parameters else [] ), ] class Parser( *error_handlers_top, # type: ignore[misc] FixMissing__future__AnnotationsImport, FixMissing__all__Attribute, FixMissingNoneHashFieldAnnotation, FixMissingImports, FilterTypingModuleAttributes, FixPEP585CollectionNames, FixTypingTypeNames, FixScipyTypeArguments, FixMissingFixedSizeImport, FixMissingEnumMembersAnnotation, OverridePrintSafeValues, *numpy_fixes, # type: ignore[misc] FixNumpyDtype, FixNumpyArrayFlags, FixCurrentModulePrefixInTypeNames, FixBuiltinTypes, RewritePybind11EnumValueRepr, FilterClassMembers, ReplaceReadWritePropertyWithField, FilterInvalidIdentifiers, FixValueReprRandomAddress, FixRedundantBuiltinsAnnotation, FilterPybindInternals, FilterPybind11ViewClasses, FixRedundantMethodsFromBuiltinObject, RemoveSelfAnnotation, FixPybind11EnumStrDoc, ExtractSignaturesFromPybind11Docstrings, ParserDispatchMixin, BaseParser, *error_handlers_bottom, # type: ignore[misc] ): pass parser = Parser() if args.enum_class_locations: parser.set_pybind11_enum_locations(dict(args.enum_class_locations)) if args.ignore_invalid_identifiers is not None: parser.set_ignored_invalid_identifiers(args.ignore_invalid_identifiers) if args.ignore_invalid_expressions is not None: parser.set_ignored_invalid_expressions(args.ignore_invalid_expressions) if args.ignore_unresolved_names is not None: parser.set_ignored_unresolved_names(args.ignore_unresolved_names) if args.print_safe_value_reprs is not None: parser.set_print_safe_value_pattern(args.print_safe_value_reprs) return parser
(args: pybind11_stubgen.CLIArgs) -> pybind11_stubgen.parser.interface.IParser
708,012
pybind11_stubgen
to_output_and_subdir
null
def to_output_and_subdir( output_dir: str, module_name: str, root_suffix: str | None ) -> tuple[Path, Path | None]: out_dir = Path(output_dir) module_path = module_name.split(".") if root_suffix is None: return out_dir.joinpath(*module_path[:-1]), None else: module_path = [f"{module_path[0]}{root_suffix}", *module_path[1:]] if len(module_path) == 1: sub_dir = Path(module_path[-1]) else: sub_dir = None return out_dir.joinpath(*module_path[:-1]), sub_dir
(output_dir: str, module_name: str, root_suffix: str | None) -> tuple[pathlib.Path, pathlib.Path | None]
708,025
port_for.exceptions
PortForException
Main port-for exception class.
class PortForException(Exception): """Main port-for exception class.""" pass
null
708,026
port_for.store
PortStore
PortStore binds, reads and stores bound ports in config.
class PortStore(object): """PortStore binds, reads and stores bound ports in config.""" def __init__(self, config_filename: str = DEFAULT_CONFIG_PATH): """Initialize PortStore.""" self._config = config_filename def bind_port( self, app: str, port: Optional[Union[int, str]] = None ) -> int: """Binds port to app in the config.""" if "=" in app or ":" in app: raise Exception('invalid app name: "%s"' % app) requested_port: Optional[str] = None if port is not None: requested_port = str(port) parser = self._get_parser() # this app already use some port; return it if parser.has_option(DEFAULTSECT, app): actual_port = parser.get(DEFAULTSECT, app) if requested_port is not None and requested_port != actual_port: msg = ( "Can't bind to port %s: %s is already associated " "with port %s" % (requested_port, app, actual_port) ) raise PortForException(msg) return int(actual_port) # port is already used by an another app app_by_port = dict((v, k) for k, v in parser.items(DEFAULTSECT)) bound_port_numbers = map(int, app_by_port.keys()) if requested_port is None: requested_port = str( select_random(exclude_ports=bound_port_numbers) ) if requested_port in app_by_port: binding_app = app_by_port[requested_port] if binding_app != app: raise PortForException( "Port %s is already used by %s!" % (requested_port, binding_app) ) # new app & new port parser.set(DEFAULTSECT, app, requested_port) self._save(parser) return int(requested_port) def unbind_port(self, app: str) -> None: """Remove port assignement to application.""" parser = self._get_parser() parser.remove_option(DEFAULTSECT, app) self._save(parser) def bound_ports(self) -> List[Tuple[str, int]]: """List all bound ports.""" return [ (app, int(port)) for app, port in self._get_parser().items(DEFAULTSECT) ] def _ensure_config_exists(self) -> None: if not os.path.exists(self._config): with open(self._config, "wb"): pass def _get_parser(self) -> ConfigParser: self._ensure_config_exists() parser = ConfigParser() parser.read(self._config) return parser def _save(self, parser: ConfigParser) -> None: with open(self._config, "wt") as f: parser.write(f)
(config_filename: str = '/etc/port-for.conf')
708,027
port_for.store
__init__
Initialize PortStore.
def __init__(self, config_filename: str = DEFAULT_CONFIG_PATH): """Initialize PortStore.""" self._config = config_filename
(self, config_filename: str = '/etc/port-for.conf')
708,028
port_for.store
_ensure_config_exists
null
def _ensure_config_exists(self) -> None: if not os.path.exists(self._config): with open(self._config, "wb"): pass
(self) -> NoneType
708,029
port_for.store
_get_parser
null
def _get_parser(self) -> ConfigParser: self._ensure_config_exists() parser = ConfigParser() parser.read(self._config) return parser
(self) -> configparser.ConfigParser
708,030
port_for.store
_save
null
def _save(self, parser: ConfigParser) -> None: with open(self._config, "wt") as f: parser.write(f)
(self, parser: configparser.ConfigParser) -> NoneType
708,031
port_for.store
bind_port
Binds port to app in the config.
def bind_port( self, app: str, port: Optional[Union[int, str]] = None ) -> int: """Binds port to app in the config.""" if "=" in app or ":" in app: raise Exception('invalid app name: "%s"' % app) requested_port: Optional[str] = None if port is not None: requested_port = str(port) parser = self._get_parser() # this app already use some port; return it if parser.has_option(DEFAULTSECT, app): actual_port = parser.get(DEFAULTSECT, app) if requested_port is not None and requested_port != actual_port: msg = ( "Can't bind to port %s: %s is already associated " "with port %s" % (requested_port, app, actual_port) ) raise PortForException(msg) return int(actual_port) # port is already used by an another app app_by_port = dict((v, k) for k, v in parser.items(DEFAULTSECT)) bound_port_numbers = map(int, app_by_port.keys()) if requested_port is None: requested_port = str( select_random(exclude_ports=bound_port_numbers) ) if requested_port in app_by_port: binding_app = app_by_port[requested_port] if binding_app != app: raise PortForException( "Port %s is already used by %s!" % (requested_port, binding_app) ) # new app & new port parser.set(DEFAULTSECT, app, requested_port) self._save(parser) return int(requested_port)
(self, app: str, port: Union[int, str, NoneType] = None) -> int