Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive class definitions in Python

I am experimenting with fluent interfaces in Python.

An example of a fluent sql query generator would look something like this in usage:

sql.select('foo').select('bar').from('sometable').tostring() 

I quickly realized that the ability to define nested classes recursively would probably help.

class sql:
    class select:        
        class select   # <--  HERE
        def __init__(self, dbcolumn, astype=None, asname=None):
            self.dbcolumn = dbcolumn
            self.astype = astype
            self.asname = asname

In the line marked with the comment '# <-- HERE':
I want this nested class reference to refer to the same 'select' class definition of the containing class.

Is this possible somehow? Maybe using some keyword that I am not aware of?

like image 478
Ries Avatar asked Oct 18 '25 02:10

Ries


1 Answers

There is no need for "recursive class definitions". All you need to do to allow chaining is to return self in your methods (or a instance of the same class if your objects are not mutable or some methods shouldn't modify the input object).

Example:

>>> class SQL(object):
...     def __init__(self):
...         self.columns = []
...     def select(self, col):
...         self.columns.append(col)
...         return self
...
>>> s = SQL()
>>> s.select('foo').select('bar').columns
['foo', 'bar']
like image 184
ThiefMaster Avatar answered Oct 20 '25 17:10

ThiefMaster