Note that there are some explanatory texts on larger screens.

plurals
  1. POString construction using OOP and Proxy pattern
    primarykey
    data
    text
    <p>I find it very interesting the way how SQLAlchemy constructing query strings, eg:</p> <pre><code>(Session.query(model.User) .filter(model.User.age &gt; 18) .order_by(model.User.age) .all()) </code></pre> <p>As far as I can see, there applied some kind of <strong>Proxy Pattern</strong>. In my small project I need to make similar string construction using OOP approach. So, I tried to reconstitute this behavior.</p> <p>Firstly, some kind of object, one of plenty similar objects:</p> <pre><code>class SomeObject(object): items = None def __init__(self): self.items = [] def __call__(self): return ' '.join(self.items) if self.items is not None else '' def a(self): self.items.append('a') return self def b(self): self.items.append('b') return self </code></pre> <p>All methods of this object return <strong>self</strong>, so I can call them in any order and unlimited number of times.</p> <p>Secondly, proxy object, that will call subject's methods if it's not a <strong>perform</strong> method, which calls object to see the resulting string.</p> <pre><code>import operator class Proxy(object): def __init__(self, some_object): self.some_object = some_object def __getattr__(self, name): self.method = operator.methodcaller(name) return self def __call__(self, *args, **kw): self.some_object = self.method(self.some_object, *args, **kw) return self def perform(self): return self.some_object() </code></pre> <p>And finally:</p> <pre><code>&gt;&gt;&gt; obj = SomeObject() &gt;&gt;&gt; p = Proxy(obj) &gt;&gt;&gt; print p.a().a().b().perform() a a b </code></pre> <p>What can you say about this implementation? Is there better ways to make the desirable amount of classes that would make such a string cunstructing with <strong>the same syntax</strong>?</p> <p>PS: Sorry for my english, it's not my primary language.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload