Reputation: 747
I wrote this little code while learning Meta classes that just registers all my class docs to a global var for all classes that have the given Meta Class:
docs = {}
def register_docs(cls):
docs[cls.__name__] = cls.__doc__
class Meta(type):
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, name, bases, class_dict)
register_docs(cls)
return cls
class RegDocs(metaclass=Meta):
'''
My Docs are here
'''
def __init__(self):
pass
print(docs)
{'RegDocs': '\n My Docs are here\n '}
Is there a way to do something similar in __init__.py
or have a "Meta Function" that can do this for a flat method file? I would like to be able to access a global
that has information about methods similar to the example below, that does some initialization on methods before being called.
func_info = {}
@metafunc
def foo():
"""
My foo docs
"""
pass
print(func_info)
> {'foo':'\n My foo docs\n '}
Upvotes: 0
Views: 604
Reputation: 61014
You could write a decorator:
func_info = {}
def metafunc(func):
func_info[func.__name__] = func.__doc__
return func
@metafunc
def foo():
"""
My foo docs
"""
pass
print(func_info)
# {'foo': '\n My foo docs\n '}
This has the advantage of also working on classes:
@metafunc
class RegDocs(metaclass=Meta):
'''
My Docs are here
'''
def __init__(self):
pass
print(func_info)
# {'foo': '\n My foo docs\n ', 'RegDocs': '\n My Docs are here\n '}
Upvotes: 1