field in list test

47 views
Skip to first unread message

Yoel Benitez Fonseca

unread,
Sep 16, 2016, 12:41:28 PM9/16/16
to web2py
Does this make sense to you?

In [1]: fields = list()

In [2]: f = db.item.id

In [3]: f in fields
Out[3]: False

In [4]: fields.append(f)

In [5]: f in fields
Out[5]: True

In [6]: f = db.item.headline

In [7]: f in fields
Out[7]: True

I mean, the last value of 'f' is a fields object but a different one.

--
Yoel Benítez Fonseca
http://redevil.cubava.cu/
$ python -c "import this"

Dave S

unread,
Sep 16, 2016, 2:43:19 PM9/16/16
to web2py-users


On Friday, September 16, 2016 at 9:41:28 AM UTC-7, Yoel Benitez Fonseca wrote:
Does this make sense to you?

Yes.
 

In [1]: fields = list()

In [2]: f = db.item.id

In [3]: f in fields
Out[3]: False

In [4]: fields.append(f)

In [5]: f in fields
Out[5]: True

In [6]: f = db.item.headline

In [7]: f in fields
Out[7]: True

I mean, the last value of 'f' is a fields object but a different one.


What you've stored in fields is an object reference; a reference to f, not to its value.

What are you trying to do?  Dynamic table handling, or forming a list of fields for SQLFORM or ??

/dps

Anthony

unread,
Sep 16, 2016, 5:02:11 PM9/16/16
to web2py-users
This is a quirk of Field objects. Field inherits from Expression, and the __eq__ method of Expression returns a Query object (rather than testing for equality and returning a boolean). So, if you do something like myfield == some_object, you do not actually get a test of whether myfield is equivalent to some_object. Instead, you just get a Query object, which apparently evaluates to True in the code Python uses to check for the existence of an element in a list. It works this way so you can create DAL queries using the db.mytable.myfield == some_value syntax.

If you want to check for a field in a list, consider instead storing the field names:

f = db.item.id
fields
= [f.name]
f
.name in fields

Or using your current code, you can do:

any(field is f for field in fields)

Above, field == f would result in the same problem, but field is f avoids the creation of the Query object.

Anthony

Yoel Benitez Fonseca

unread,
Sep 20, 2016, 10:48:13 AM9/20/16
to web2py
Thanks Anthony ... I'm sorry say but can not remember for what i
needed that code snippet .... thanks any way.. is good to know that
stuff.
> --
> Resources:
> - http://web2py.com
> - http://web2py.com/book (Documentation)
> - http://github.com/web2py/web2py (Source code)
> - https://code.google.com/p/web2py/issues/list (Report Issues)
> ---
> You received this message because you are subscribed to the Google Groups
> "web2py-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to web2py+un...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages