2
   class test:
      a="hi"

      def msg(self):
          print the variable for which the object is referring to

   t= test()
    print t.b

From the above code is there any way to tell that the object is referring to a variable b which does not exist

2
  • well,you get AttribuiteError if you refer a variable which does not exist. Commented Mar 9, 2011 at 6:07
  • 1
    "it's easier to ask for forgiveness than permission" Commented Mar 9, 2011 at 7:20

5 Answers 5

3

Use the __getattr__ method, see documentation:

In [1]: class test(object):
   ...:     a = 'hi'
   ...:     def __getattr__(self, val):
   ...:         print 'you are accessing ', val
   ...:         
   ...:         

In [2]: t = test()

In [3]: t.b
you are accessing  b

In [4]: t.c
you are accessing  c

In [5]: t.a
Out[5]: 'hi'

EDIT:

class test(object):
    a = 'hi'

    def msg(self, var, default='undefined'):
        setattr(self, var, default)
        return default

    def __getattr__(self, val):
        print 'attribute %s not found, setting..' % val
        return self.msg(val)


>>> t = test()
>>> print t.a
'hi'
>>> print t.b
'attribute b not found, setting..'
'undefined'
>>> t.b = 'this is black magic'
>>> # notice no message is printed here about attribute not found
>>> print t.b
'this is black magic'

EDIT2:

>>> d = {'a': '1'}
>>> d.setdefault('b', 'b')
'b'
>>> d
{'a': '1', 'b': 'b'}
>>> d.setdefault('a', 'b')
'1'
>>> d
{'a': '1', 'b': 'b'}
Sign up to request clarification or add additional context in comments.

17 Comments

In the statement hasattr(t, 'b') instead of hard coding b cant we get the variable from the object itself
Or how will the object know that the variable b is being reffered
Can you please clarify what you mean? In your question, you asked how to check if the object is referring to a variable b which does not exist. @Cameron's answer shows you how to catch an exception. What are you trying to do exactly?
So in my class i need to print that the object is referring to a variable which does not exist..Please see the edit in the question
Can __getattr__(self, val) print 'you are accessing ', val be defined in msg() some how.So i can access it in msg function
|
1

Yes. You will get a NameError on the print b line, and an AttributeError on the print t.b line.

You can catch these exceptions like this:

try:
    print t.b
except AttributeError as e:    # or `except AttributeError, e` on Python < 2.6
    # Do something...

1 Comment

How will the object know that its being referred to a variable which does not exist
1

This should do it.

class tester(object):
    a = 'hi'

    def __getattr__(self, val):
        print 'accessing attribute %s failed!' % val

>>> t = tester()
>>> t.a
'hi'
>>> t.b
accessing attribute b failed!
>>> 

EDIT: Removed some redundant code

2 Comments

That is replicating the standard behavior. What good is that?
Good call. I didn't realise that. Thanks!
0

If that's all the code, then of course there is no b. But, I assume that you want us to assume there could be more code. If there is, or perhaps if this code is imported as a module by other code, then there is no way to tell until it is run.

Comments

0

All members of an object are stored in that objects __dir__. So you can just do this:

>>> "msg" in dir(t)
True
>>> "b" in dir(t)
False

This works for the standard case, and may behave differently if descriptors are involved, or __getattr__ or __getattribute__ are overloaded.

1 Comment

The first line is not correct, as you say yourself in the last line. __dir__ is a way for an object to report the attributes it wants you to know about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.