Invalid properties don't throw errors?

16 views
Skip to first unread message

Aaron C. de Bruyn

unread,
Nov 23, 2012, 4:31:45 PM11/23/12
to django...@googlegroups.com
I'm stumped.

I have a Django project that's fairly far along--I'm able to use it internally.

A few days ago while trying to debug a function, I noticed I was settings a property incorrectly.

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> u = User.objects.get(pk=1)
>>> u.user = 'test'
>>> 

No error.  It should be 'u.username'.

So I tried a few more.

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> u = User.objects.get(pk=1)
>>> u.sdbgnois74gn = 'test'
>>> 

No error is thrown for trying to set an invalid property.

I tried blowing away my virtualenv and reinstalling.  Same issue.

Passing invalid parameters while creating a new object throws errors, but not after the object is created.

>>> django.VERSION
(1, 4, 2, 'final', 0)
>>> c = Company(doesnotexist='123')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/aaron/.virtualenvs/tapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 367, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'doesnotexist' is an invalid keyword argument for this function
>>> c = Company(name='123')
>>> c.doesnotexist = '123'
>>>

I have never witnessed this behavior before in python.  Any pointers on where I should start digging?

-A

Tim Chase

unread,
Nov 23, 2012, 4:56:30 PM11/23/12
to django...@googlegroups.com, Aaron C. de Bruyn
On 11/23/12 15:31, Aaron C. de Bruyn wrote:
> Python 2.7.3 (default, Aug 1 2012, 05:14:39)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> (InteractiveConsole)
>>>> u = User.objects.get(pk=1)
>>>> u.user = 'test'
>>>>
>
> No error. It should be 'u.username'.

This is a Python thing, not limited to Django, and fully expected:

Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass(object): pass
...
>>> c = MyClass()
>>> c.doesnotexist = 42

Barring some particular situations (you may want to read up on
__slots__), you can dynamically add any property you want to an
object/class. Python is less forgiving if you *read* nonexistent
properties:

>>> print c.no_property_here
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'no_property_here'


-tkc







Reply all
Reply to author
Forward
0 new messages