Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Hybrid Value Object, Query Tuple Results

I am trying to follow the examples from the documentation on building custom comparators using hybrid value objects,

class CaseInsensitiveWord(Comparator):
    "Hybrid value representing a lower case representation of a word."

    def __init__(self, word):
        if isinstance(word, basestring):
            self.word = word.lower()
        elif isinstance(word, CaseInsensitiveWord):
            self.word = word.word
        else:
            self.word = func.lower(word)

    def operate(self, op, other):
        if not isinstance(other, CaseInsensitiveWord):
            other = CaseInsensitiveWord(other)
        return op(self.word, other.word)

    def __clause_element__(self):
        return self.word

    def __str__(self):
        return self.word

    key = 'word'
    "Label to apply to Query tuple results"

I don't understand, however, why this was added to the end of the class definition:

key = 'word'
"Label to apply to Query tuple results"

What is this for?

like image 845
john Avatar asked Jan 23 '26 10:01

john


1 Answers

While it's not a fully baked Python feature, a convention is to comment attributes in the same way as functions and methods, i.e. by placing a string below the attribute. Comments like the above are picked up by tools like Sphinx. You can see examples of these docstrings getting generated in places like http://www.sqlalchemy.org/docs/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.class_manager.

edit: oh why it has an actual ".key". When you say:

for row in session.query(MyClass.mycustomthing, MyClass.myothercustomthing):
   print row.word, row.someotherword

the "word" and "someotherword" tuple keys are the value of ".key" on each comparator. if you were to call label() on it, that would change it to something else. I don't know that it's strictly necessary to be there at all.

like image 127
zzzeek Avatar answered Jan 24 '26 23:01

zzzeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!