NenadK
NenadK

Reputation: 391

Python best practice: class definition inside function?

I am in a situation where the structure returned by a function will likely not need to be used anywhere outside of that function. However since it's not a simple value but an actual object I would like to declare a class inside my function that I can instantiate then return.

eg:

def CreateSomeFunkyDataStructure():

    class FunkyClass:
        def __init__(self):
            self.var1 = 'Play that funky music white boy.'

        def getFunky(self):
            print 'Play that funky music right.'


    x = FunkyClass()

    return x


o = CreateSomeFunkyDataStructure()

print o.var1
o.getFunky()

My question is whether this is a good practice or a bad one since this just feels strange. At the same time it seems to me that because the purpose of encapsulation is to prevent someone from accessing the implementation of a function, in this case it might be quite appropriate. If the class is not something that will be required anywhere else in the program, there is no reason for the rest of the program to have access to it.

Upvotes: 3

Views: 2086

Answers (1)

Eric
Eric

Reputation: 97601

This is bad because it makes the following break:

  1. Type-checking, with isinstance(result, FunkyClass)
    Furthermore, the results of invoking CreateSomeFunkyDataStructure multiple times will not even be of the same type! (ie, type(f1) is not type(f2))
  2. Invoking members statically, with map(FunkyClass.getFunky, [funcy1, funcy2])
  3. pickleing
    This requires classes to be visible at module scope - even nested classes cause it to choke

Upvotes: 5

Related Questions