Last active
February 4, 2020 13:22
-
-
Save crcrpar/8034630f1d4f9d1f9de4d449185728e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
from typing import (Any, Callable, Tuple) | |
def str_func_name_args( | |
func: Callable[[Any], Any] | |
) -> Tuple[str, Callable[[Any], Any]]: | |
name = func.__name__ | |
argspec = inspect.getfullargspec(func) | |
n_defaults = len(argspec.defaults) if argspec.defaults is not None else 0 | |
if n_defaults > 0: | |
args = ', '.join(argspec.args[:-n_defaults]) | |
with_default_values = ', '.join( | |
[ | |
'{}={}'.format(a, d) | |
for a, d in zip(argspec.args[-n_defaults:], argspec.defaults) | |
] | |
) | |
else: | |
args = ', '.join(argspec.args) | |
with_default_values = '' | |
if len(args) > 0 and len(with_default_values) > 0: | |
args += ', ' | |
func_name_args = name + '(' + args + with_default_values + ')' | |
func.__doc__ = func_name_args + '\n\n' + func.__doc__ | |
return func_name_args, func | |
def foo(a: int, b: float, c: float) -> None: | |
"""Foo. | |
Args: | |
a: | |
b: | |
c: | |
""" | |
def baz(g, d: int = 100, e: float = 0.0) -> float: | |
"""Baz | |
Args: | |
d: | |
e: | |
""" | |
return d + e | |
class Bar(object): | |
"""Bar. | |
Args: | |
a: | |
b: | |
c: | |
""" | |
def __init__(self, a, b, c) -> None: | |
pass | |
if __name__ == '__main__': | |
foo_ = str_func_name_args(foo) | |
print(foo_[1].__doc__) | |
print(str_func_name_args(baz)) | |
# print(str_func_name_args(Bar.__init__)) | |
print(type(Bar), type(Bar.__init__), type(foo)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foo(a, b, c) | |
Foo. | |
Args: | |
a: | |
b: | |
c: | |
('baz(g, d=100, e=0.0)', <function baz at 0x10e7c3a70>) | |
<class 'type'> <class 'function'> <class 'function'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment