Naming convention for functions instancing classes

Viewed 192

I have implemented a simple version of the factory pattern using functions as factories. These functions naturally return class instances.

What would be the correct naming convention for such functions returning a class instance?

class ExampleClass0:
    pass

class ExampleClass1:
    pass

class ExampleClassDefault:
    pass

def ExampleClass(param):
    if param == 0:
       return ExampleClass0()
    elif param == 1:
       return ExampleClass1()
    else
       return ExampleClassDefault()

object0 = ExampleClass(0)
object1 = ExampleClass(1)
object2 = ExampleClass(2)

According to PEP8, ExampleClass should be named as example_class, but to me it is much clearer if it is named as if it were a class, because at the end of the day it is acting as a class.

2 Answers

I believe that in this case, it is quite justified to deviate from PEP 8. This practice is not very common, but there are examples of its use. For example, an excerpt from Django Coding style:

Use InitialCaps for class names (or for factory functions that return classes).

Example from django sources:

class DeserializationError(Exception):
    """Something bad happened during deserialization."""

    @classmethod
    def WithData(cls, original_exc, model, fk, field_value):
        """
        Factory method for creating a deserialization error which has a more
        explanatory message.
        """
        return cls("%s: (%s:pk=%s) field_value was '%s'" % (original_exc, model, fk, field_value))

For me when first met with python, I try to figure out how is best practice with code convention and I really fall with this [Google style guide][1] which is quiet useful. in the next table (img) you'll find some recommendation:

Guidelines derived from Guido’s Recommendations

Related