4

Possible Duplicate:
getattr on a module

I have a module which defines a Manager class in it. I would like the module to create an instance of this class and have the module serve as a "global instance" of this class. For example:

class Manager:

    def func(self):
        print('stuff')

instance = Manager()

def func():
    instance.func()

Is there a way to make module.x returns module.instance.x? (kind of like a module level property)

UPDATE: The answer in this question covers only half of my use case (i.e., it is NOT a duplicate, what that question is asking is different); I also need the module's attribute to also be available. Example:

class Manager:

    def __init__(self):
        self.x = 3

    def func(self):
        print('stuff')

sys.modules[__name__] = Manager()

>>> module.func
<func>
>>> module.x
3
>>> module.Manager
AttributeError
Community
  • 1
  • 1
darkfeline
  • 9,404
  • 5
  • 31
  • 32
  • If you don't need any fancy class functionality like `__getattr__` then why not simply use module-level functions instead of methods? – yak Sep 30 '12 at 04:40
  • I need "fancy class functionality" such as subclassing/inheritance and making more instances. I know it seems like I want a singleton, but I don't. I want a regular class whose module has a "global instance" of it. – darkfeline Sep 30 '12 at 05:30
  • In that case consider writing functions that would delegate to the main instance. You could also simply do `foo = instance.foo` for each method. – yak Sep 30 '12 at 06:04
  • `instance.foo = 3; foo = instance.foo; instance.foo = 4; foo == 3 and instance.foo = 4` I considered writing functions, but that would mean a set and a get for EACH attribute. Lots of bloat. – darkfeline Sep 30 '12 at 06:27
  • Oy, I specifically edited my question to state that this is NOT a duplicate of the getattr question, yet it is marked as duplicate? What is wrong with you people? – darkfeline Sep 30 '12 at 19:32
  • 1
    Look at what Python's `logging` class does. Define the class and create an instance of the class within the module. `import logging; logging.getLogger().warn(...)` can be called in every file that you want to have logging for, and they will all share the same instance as long as you access it via `logging.getLogger()` instead of creating a local instance in your file (ie, don't do `log = logging.getLogger()`) – IceArdor Dec 13 '13 at 02:29
  • @IceArdor I think that's a nice idea, I was thinking the same because I also use `logging`...but maybe not really fair to @darkfeline because the module `logging` already has a `getLogger` defined and for `Manager` it is not just available. – Adriaan Jun 04 '20 at 13:30

1 Answers1

0

Why not have the Manager's __getattr__ return module-level objects?

def __getattr__(self, key):
    try:
        return globals()[key]
    except KeyError:
        raise AttributeError(key)
nneonneo
  • 171,345
  • 36
  • 312
  • 383