mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Add sphinx.util.inspect:getslots() to get __slots__ attribute
This commit is contained in:
parent
4c582b3d66
commit
bbb0ea5f12
@ -137,6 +137,27 @@ def unwrap_all(obj: Any, *, stop: Callable = None) -> Any:
|
||||
return obj
|
||||
|
||||
|
||||
def getslots(obj: Any) -> Optional[Dict]:
|
||||
"""Get __slots__ attribute of the class as dict.
|
||||
|
||||
Return None if gienv *obj* does not have __slots__.
|
||||
"""
|
||||
if not inspect.isclass(obj):
|
||||
raise TypeError
|
||||
|
||||
__slots__ = safe_getattr(obj, '__slots__', None)
|
||||
if __slots__ is None:
|
||||
return None
|
||||
elif isinstance(__slots__, dict):
|
||||
return __slots__
|
||||
elif isinstance(__slots__, str):
|
||||
return {__slots__: None}
|
||||
elif isinstance(__slots__, (list, tuple)):
|
||||
return {e: None for e in __slots__}
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
|
||||
def isenumclass(x: Any) -> bool:
|
||||
"""Check if the object is subclass of enum."""
|
||||
return inspect.isclass(x) and issubclass(x, enum.Enum)
|
||||
|
@ -493,6 +493,28 @@ def test_dict_customtype():
|
||||
assert "<CustomType(2)>: 2" in description
|
||||
|
||||
|
||||
def test_getslots():
|
||||
class Foo:
|
||||
pass
|
||||
|
||||
class Bar:
|
||||
__slots__ = ['attr']
|
||||
|
||||
class Baz:
|
||||
__slots__ = {'attr': 'docstring'}
|
||||
|
||||
class Qux:
|
||||
__slots__ = 'attr'
|
||||
|
||||
assert inspect.getslots(Foo) is None
|
||||
assert inspect.getslots(Bar) == {'attr': None}
|
||||
assert inspect.getslots(Baz) == {'attr': 'docstring'}
|
||||
assert inspect.getslots(Qux) == {'attr': None}
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
inspect.getslots(Bar())
|
||||
|
||||
|
||||
@pytest.mark.sphinx(testroot='ext-autodoc')
|
||||
def test_isclassmethod(app):
|
||||
from target.methods import Base, Inherited
|
||||
|
Loading…
Reference in New Issue
Block a user