0

I'm adding dynamically attribute to a module, before using it I want to verify that the added attribute exist (in the module).

hasattr signature is:

hasattr(object, name)

module is not an object, so how can I verify the existence of the added attribute ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
EitanG
  • 221
  • 4
  • 19

4 Answers4

11

A Python module is an object. hasattr() works just fine on that.

Demo:

>>> import os
>>> type(os)
<type 'module'>
>>> os
<module 'os' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/os.pyc'>
>>> hasattr(os, 'sep')
True
>>> hasattr(os, 'foobar')
False

If you have a string with the module name, then you can look up the module object in the sys.modules mapping:

>>> import sys
>>> sys.modules['os']
<module 'os' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/os.pyc'>
 >>> hasattr(sys.modules['os'], 'sep')
True
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for your answer. I need some key word for the module name. If for example my module is called 'MyModule' and I want to see if attribute 'MyAttribute' is exist, I want NOT to check it by hasattr('MyModule', 'MyAttribute') but by some key word that will recognize the module name - hasattr(key word, 'MyAttribute'). – EitanG Oct 22 '13 at 07:43
  • @EitanG: You can look up modules by name in the `sys.modules` mapping: `hasattr(sys.modules[modulename], 'MyAttribute')`. – Martijn Pieters Oct 22 '13 at 08:40
2
>>> import os
>>> hasattr(os, 'path')
True
>>>

As you seen hasattr works on modules (everything is an object in python, including functions and modules).

sloth
  • 99,095
  • 21
  • 171
  • 219
1

Why not?

>>> import sys

>>> sys.modules['sys']
<module 'sys' (built-in)>

>>> type(sys.modules['sys'])
<type 'module'>

>>> hasattr(sys, 'argv')
True
alko
  • 46,136
  • 12
  • 94
  • 102
0

Actually, it is an object. Everything in python is an object. Look at this question as well.

    >>>import os
    >>>issubclass(type(os), object)
    True
    >>>hasattr(os, 'kill')
    True
    >>>
Community
  • 1
  • 1
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31