Search code examples
pythonclassoopinitializationpython-import

Ensuring the absence of an __init__ function in Python


I'm writing a plugin-based application. Part of the specification for a plugin is that a plugin must not implement the __init__ method, as any initialization needs to be handled by the plugin manager, not the plugin itself. (A plugin writer would define their startup code in another method, called by the plugin manager after some checks are satisfied.)

To enforce this style, the plugin manager should fail, throw an exception, or perform some other discouraging action if __init__ is being used.

I thought I could just check to see if __init__ is defined:

# minimaltest.py
__meta__ = "Minmimal metadata"
# main.py
import minimaltest
hasattr(minimaltest, '__meta__')  # => True
hasattr(minimaltest, '__somethingimadeup__')  # => False
hasattr(minimaltest, '__init__')  # => True?!

Problem: That hasattr call always returns True

How can I make sure that any prospective plugin script has not implemented the __init__ method?


Solution

  • The hasattr returns True for the presence of __init__ because the minimal class we created inherits from Object, which comes with that method defined.

    If we want to see what methods our minimal class has, without getting the methods its superclass has defined, you can call __dict__ and get a list that's simple to test against using .keys:

    if '__init__' in minimal.__dict__.keys():
        raise RuntimeError("Plugins may not define __init__ methods")