I am creating a class that inherits from collections.UserList
that has some functionality very similar to NumPy's ndarray
(just for exercise purposes). I've run into a bit of a roadblock regarding recursive functions involving the modification of class attributes:
Let's take the flatten
method, for example:
class Array(UserList):
def __init__(self, initlist):
self.data = initlist
def flatten(self):
# recursive function
...
Above, you can see that there is a singular parameter in the flatten
method, being the required self
parameter. Ideally, a recursive function should take a parameter which is passed recursively through the function. So, for example, it might take a lst
parameter, making the signature:
Array.flatten(self, lst)
This solves the problem of having to set lst
to self.data
, which consequently will not work recursively, because self.data
won't be changed. However, having that parameter in the function is going to be ugly in use and hinder the user experience of an end user who may be using the function.
So, this is the solution I've come up with:
def flatten(self):
self.data = self.__flatten(self.data)
def __flatten(self, lst):
...
return result
Another solution could be to nest __flatten
in flatten
, like so:
def flatten(self):
def __flatten(lst):
...
return result
self.data = __flatten(self.data)
However, I'm not sure if nesting would be the most readable as flatten
is not the only recursive function in my class, so it could get messy pretty quickly.
Does anyone have any other suggestions? I'd love to know your thoughts, thank you!