2

Is there a "pythonic" way to use an instance of a class for a module. For example:

class MyClass:
   def __init__(self):
       self.my_var = "cool value"

_instance = MyClass()

def getInstance():
    return _instance()

The goal is to share large lookup classes through the application instead of initializing them on every import.

5
  • 1
    "instead of initializing them on every import" - this part of your question suggests that you may have a bad mental model of how Python's import system works. Python will not redo module initialization on every import; a module is already shared between all other modules that import it. Commented Jul 11, 2017 at 23:27
  • 1
    I'm not following what you mean by "share large lookup classes through the application". Care to give an example of how you envisage this might be used? Commented Jul 11, 2017 at 23:38
  • 3
    This smells like Java to me... Commented Jul 11, 2017 at 23:39
  • What's the point of the getInstance function? Note, it throws an error, since you return the result of calling _instance, but MyClass objects aren't callable... Commented Jul 11, 2017 at 23:46
  • To answer all these questions I wanted to do what is in the answer below. Still not used to import in python. Commented Jul 12, 2017 at 20:59

2 Answers 2

3

You can import anything from a module. Class instance is not an exception:

file1.py

class MyClass:
   def __init__(self):
       self.my_var = "cool value"

instance = MyClass()

file2.py

from file1 import instance
Sign up to request clarification or add additional context in comments.

Comments

0

If your instances are dynamically created somehow, and you really need to keep track of them, you can override __new__, like this:

class MyClass:
    instances = []

    def __new__(cls, *args, **kwargs):
        my_instance = super(MyClass, cls).__new__(cls, *args, **kwargs)
        MyClass.instances.append(my_instance)
        return my_instance

a = MyClass()

print(MyClass.instances)

1 Comment

Good idea but I don't think I should mask what is really happening like this. Maybe if I was packaging this for an external project to use.

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.