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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With