0

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 '}

1 Answer 1

1

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    '}
2
  • Thanks, follow up. If I was importing a flat file and had init.py import os and my function decorator call` os.remove("./*")` would that be triggered if someone used import evil_package or from evil_package import *? Curious about security issues with using these meta objects.
    – bison
    Commented Aug 15, 2018 at 1:31
  • So this doesn't have anything to do with meta classes or decorators. Whenever you import, you're executing a Python file. That file can do more or less anything. Commented Aug 15, 2018 at 1:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.