15

So, I'm writing a module for connecting to external account providers (Twitter, Facebook etc) and I have a superclass that is useless on its own, but contains generic methods that need to be invoked by the subclasses for persisting auth tokens, getting auth tokens and deauthorizing the provider. My question is, is there a way to make it uninstantiable or should I follow the consenting adults rule and just let anyone who uses it make mistakes as they see fit? Other than a docstring is there a good way to denote that someone shouldn't use this superclass on its own?

2
  • Is it really not possible just to declare the class abstract in python? Jun 7, 2011 at 12:43
  • @bjarkef: Have you looked at AFoglia's answer?
    – JAB
    Jun 7, 2011 at 14:24

4 Answers 4

7

I'm seconding Sven Marnach's edit: I think you should follow the "consenting adults" rule and mention in the docstring that the class is not meant to be instantiated.

The key phrase in your question is "I have a superclass that is useless on its own." It won't invoke cthulhu when instantiated; it won't cause some kind of catastrophic, hard-to-debug failure somewhere else in your program; it will just be a minor waste of time. That's not worth crippling the class for, I think.

2
  • If I had to choose an "accepted answer", I'd go for this one! Jun 6, 2011 at 20:04
  • I like all the other answers, but they seem too unpythonic. I think @senderle is right. I'll put info in the docstring and hope people take the time to read it.
    – tiny_mouse
    Jun 6, 2011 at 20:45
7
class NoInstantiation:    # "class NoInstantiation(object):" in Python 2.2+ or whatever
    def __new__(cls):
        "This class is not meant to be instantiated, so __new__ returns None."
        return None

This won't stop people from overriding that functionality if they want to, but it should be a fairly decent method of preventing accidental instantiation. If someone does accidentally call it, well, they can't say you didn't warn them.

EDIT: If you really wanted to be nice, you could also print a warning to stderr in __new__() about it or even throw an exception.

EDIT 2: If you go the exception route, you may want to raise the exception within the __init__() method of the superclass instead, as users will likely be overriding __init__() in their subclasses anyway.

EDIT 3: There's also the option of setting __new__ or __init__ equal to None, though the resultant error wouldn't be very informative.

7
  • 3
    1. This does not work in Python 2.x. __new__() is only invoked for new-style classes, so you have to derive from object. 2. You should raise an error instead of returning None. 3. This requires all derived classes to overwrite __new__(), which does not seem to be very convenient. Jun 6, 2011 at 18:54
  • @Sven: Ah, right, made a note about Python 2. As for requiring all derived classes to overwrite __new__()... It just requires calling object.__new__(). I'll make a note about another way of doing that, though.
    – JAB
    Jun 6, 2011 at 19:00
  • @JAB: If NoInstantiation has base classes, you might need to call the __new__() method of one of the base classes, which might be hard to figure out in ar derived class. Jun 6, 2011 at 19:05
  • I would recommend going the route of raising an error. Printed warning messages are not effective from my experience. It would be best to do it on __init__ as mentioned in EDIT #2.
    – Jesse Webb
    Jun 6, 2011 at 19:07
  • @JAB: I posted a suggestion how to improve this. I first tried to fit this in a comment, but it just didn't work :) Jun 6, 2011 at 19:08
7

Building on JAB's answer, it might be more convenient to write __new__() like this:

class NoInstantiation(object):
    def __new__(cls, *args, **kwargs):
        if cls is NoInstantiation:
            raise RuntimeError(
                "NoInstantiation isn't meant to be instantiated")
        else:
            return super(NoInstantiation, cls).__new__(cls, *args, **kwargs)

That way, you don't need to overwrite __new__() in derived classes.

Edit: I posted this answer as an improvement of JAB's answer, but I would recommend against actually using the above code. It's somehow intentionally crippling your class. The usual Python way is to clearly document the class is not meant to be instatntiated. But maybe someone finds a way how this is useful anyway -- you never know in what ways people will use your library.

2
  • I agree, I don't think that is the real "Pythonic" approach. Python, at least as it was originally conceived, very much believed in the "We're all consenting adults" mentality. Read Von Rossum's original statements about strong vs. weak typing -- his reasoning behind rejecting typed arguments is that "if someone wants to abuse your code, that is their problem." My suggestion: Put a print statement in there saying, "This class is generally useless on its own. Use at your own risk." (in addition to the docstring) Jun 6, 2011 at 20:05
  • @cwallenpoole: Python is strongly typed. You probably meant "static vs. dynamic typing". Jun 6, 2011 at 20:08
4

You could use the abstractmethod decorator in the abc module to mark one of the methods that all of the derived classes override as abstract.

In [1]: import abc

In [2]: class C:
   ...:     __metaclass__ = abc.ABCMeta
   ...:     
   ...:     @abc.abstractmethod
   ...:     def my_abstract_method(self, *args) :
   ...:         pass
   ...:     
   ...:     

In [3]: c = C()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/afoglia/<ipython console> in <module>()

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

I do question the class organization though. If this "superclass" is nothing but functions that need to be invoked by subclasses, why is it not just a module that the different mechanism can use? If it's a definition of an interface that derived classes fully implement, (perhaps as a template method pattern), then the abstract methods represent functions that need to be given implementations by the derived class. In that case, I wouldn't even bother making the base non-constructible, and either have people get the necessary derived through a factory method, or let the user figure it out when he calls a function that fails. (Do put a comment in the docstrings though.)

1
  • You may be right in that I might want to rethink the class structure, but I'm not sure. The superclass has both methods that need to be overwritten as well as methods that every subclass should invoke to achieve the same authentication. I guess I could flip it so the TwitterClient and FacebookClient classes are subs of an interface, but the stateful bits/methods of the superclass could be a completely separate class that each one has as its own instance for CRUD actions on auth tokens for users. Maybe I'm just doing it wrong. ;)
    – tiny_mouse
    Jun 8, 2011 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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