How can I test to see if a class contains a particular attribute?
- by BryanWheelock
How can I test to see if a class contains a particular attribute?
In [14]: user = User.objects.get(pk=2)
In [18]: user.__dict__
Out[18]:
{'date_joined': datetime.datetime(2010, 3, 17, 15, 20, 45),
'email': u'[email protected]',
'first_name': u'',
'id': 2L,
'is_active': 1,
'is_staff': 0,
'is_superuser': 0,
'last_login': datetime.datetime(2010, 3, 17, 16, 15, 35),
'last_name': u'',
'password': u'sha1$44a2055f5',
'username': u'DickCheney'}
In [25]: hasattr(user, 'username')
Out[25]: True
In [26]: hasattr(User, 'username')
Out[26]: False
I'm having a weird bug where more attributes are showing up than I actually define.
I want to conditionally stop this.
e.g.
if not hasattr(User, 'karma'):
User.add_to_class('karma', models.PositiveIntegerField(default=1))