Alter a value as its added?

8 views
Skip to first unread message

Phillip B Oldham

unread,
Apr 12, 2010, 5:24:13 PM4/12/10
to MongoKit
I have an attribute that I need to ensure is lowercase, but I don't
want to have to set a specific type; I'd prefer to set it simply as a
unicode value but have it set/stored as lowercase without having to
"do" anything.

For instance:

>>> class Doc(Document):
... structure = { 'name': unicode }
...
>>> doc = db.mycol.Doc()
>>> doc
{ 'name': None }
>>> doc.name = 'FooBar'
>>> doc.save()
>>> doc
{ 'name': 'foobar' }

Is there a way I can do this without having to change the structure or
type?

Peter Bengtsson

unread,
Apr 12, 2010, 7:16:03 PM4/12/10
to mong...@googlegroups.com
Would this work?

class Doc(Document):
def save(self, *args, **kwargs):
self.name = self.name.lower()
super(Doc, self).save(*args, **kwargs)

> --
> To unsubscribe, reply using "remove me" as the subject.
>

--
Peter Bengtsson,
work www.fry-it.com
home www.peterbe.com
hobby www.issuetrackerproduct.com
fun crosstips.org

Phillip B Oldham

unread,
Apr 13, 2010, 3:11:21 AM4/13/10
to MongoKit
On Apr 13, 12:16 am, Peter Bengtsson <pete...@gmail.com> wrote:
> Would this work?
>
> class Doc(Document):
>     def save(self, *args, **kwargs):
>         self.name = self.name.lower()
>         super(Doc, self).save(*args, **kwargs)

Yep; I just remembered about this when I woke up this morning.

However, thinking on I think it might be useful to define "filters"
for setting values... maybe something like:

>>> class Doc(Document):
... structure = { 'name': unicode }

... filters = { 'name': self._set_name }
... def _set_name(self, val):
... return unicode(val.lower())
...
>>> d = Doc()
>>> d.name = 'FooBar'
>>> d
{ 'name': u'foobar' }
>>> d.save()

Could help with unit-testing when there are many attributes which need
to be "cleaned" or adjusted when being set. Just a thought.

Peter Bengtsson

unread,
Apr 13, 2010, 5:11:16 AM4/13/10
to mong...@googlegroups.com
Nicholas,

See below for Phillip's suggestion.
I've been lacking something like this too.
Overriding the save method is quite pythonic and works but it's far from neat.

I often want to do little basic manipulations of values before setting
them. For example turning byte strings into unicode and stripping
whitespace.
Any thoughts on this?

--

Nicolas Clairon

unread,
Apr 13, 2010, 8:24:16 AM4/13/10
to mong...@googlegroups.com
Good Idea. i file a ticket here :
http://bitbucket.org/namlook/mongokit/issue/47/implement-filters-descriptor

Feel free to discuss this feature before implementation.

Nicolas Clairon

unread,
Apr 28, 2010, 9:28:36 AM4/28/10
to mong...@googlegroups.com
If there is enough request for this feature, I will implement it (to
vote, leave a comment here
http://bitbucket.org/namlook/mongokit/issue/47/implement-filters-descriptor)

Also, you can send patch ;-)
Reply all
Reply to author
Forward
0 new messages