__getattr__ equivalent for a module

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Maksim Kasimov

    #1

    __getattr__ equivalent for a module

    Hi,

    in any python class it is possible to define __getattr__ method so that if we try to get some value of not actually exists instance attribute, we can get some default value.

    For example:

    class MyClass:

    def __getattr__(sel f, attname):

    if attname.startsw ith('a'):
    return "*"


    i = MyClass()
    ....
    i.aValue # it gives "*" if "i.aValue" will not be set before this call


    i need to define the same behavior for a module:

    import mymodule
    mymodule.anyatt ribute
    or
    from mymodule import anyattribute

    "anyattribu te" is not actually defined in the module, but gives some attribute of the module

    so my question is: how to tune up a module get default attribute if we try to get access to not actually exists attribute of a module?

    (python 2.4 or 2.2)

    many thanks for help.


    --
    Maksim Kasimov
  • Leif K-Brooks

    #2
    Re: __getattr__ equivalent for a module

    Maksim Kasimov wrote:
    so my question is: how to tune up a module get default attribute if we
    try to get access to not actually exists attribute of a module?
    You could wrap it in an object, but that's a bit of a hack.

    import sys

    class Foo(object):
    def __init__(self, wrapped):
    self.wrapped = wrapped

    def __getattr__(sel f, name):
    try:
    return getattr(self.wr apped, name)
    except AttributeError:
    return 'default'

    sys.modules[__name__] = Foo(sys.modules[__name__])

    Comment

    • Maksim Kasimov

      #3
      Re: __getattr__ equivalent for a module


      Hi Leif, many thanks - it works

      Leif K-Brooks wrote:
      Maksim Kasimov wrote:
      >so my question is: how to tune up a module get default attribute if we
      >try to get access to not actually exists attribute of a module?
      >
      You could wrap it in an object, but that's a bit of a hack.
      >
      import sys
      >
      class Foo(object):
      def __init__(self, wrapped):
      self.wrapped = wrapped
      >
      def __getattr__(sel f, name):
      try:
      return getattr(self.wr apped, name)
      except AttributeError:
      return 'default'
      >
      sys.modules[__name__] = Foo(sys.modules[__name__])

      --
      Maksim Kasimov

      Comment

      Working...