Question

I would like to keep tab-completion on my module clean. I have a function which returns a class. Since that class is only accessible through the function, I was thinking of nesting the class inside the function to hide it from the module in which the function is defined. Would there be any reasons not to do this or alternative approaches that you would recommend?

Rough code:

def search():

     #Nested class
     #------------------------------
     class SearchResult():

          def __init__(self, data):
                  #do stuff
     #---------------------------------       

     #do stuff - define data

     return SearchResult(data)
Was it helpful?

Solution

A downside to having the class defined inside the function is that there is no way to reference it from elsewhere. For instance, your other code can't use isinstance to test if a value is a SearchResult instance, since they have no way to reference the SearchResult class.

Another issue is that your return values won't technically be of the same type! That's because each time the search function is run, it creates its own SearchResult class that is different from the SearchResult classes created by each other run. So, if you had two results, a and b, type(a) == type(b) would be false. This isn't likely to matter in most cases, but it might occasionally become awkward.

If the only reason you have for doing things this way is that you don't want the class showing up in your tab-completion list, you might be able to hide it a better way (though exactly how may depend on what IDE you're using and how its tab-completion works). Something you might want to try is prefixing the class name with an underscore (_SearchResult), which may make the tab-completion ignore it since a leading underscore is conventionally understood to indicate that something is "private".

OTHER TIPS

There are a few downsides. For every call of search, you will create a new SearchResult class, distinct from the others, so, e.g.:

>>> result_1 = search()
>>> result_2 = search()
>>> type(result_1) == type(result_2)
False

Admittedly, you probably should not be doing this in your code, but keep in mind that each class also takes up memory, though that, too, may be insignificant. Defining the class locally also makes it inaccessible globally, which might be useful when debugging your code.

I'd echo chepner's recommendation to define SearchResult globally, but maybe prefix it with an underscore to emphasize that it is internal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top