2

I have a class that looks something like this:

class Foo:
    import_extra = false

    def __init__(import_extra):
        if import_extra:
            self.import_extra = true
            import extra

    def do_thing():
        # do some stuff

        if self.import_extra:
            extra.do_extra_stuff()

This class has some functionality that depends on extra, but I want to be able to decide whether this functionality is available or not when I first initialize the class, which happens once at the start of running the application. Unfortunately, I can't seem to figure out how to import extra for the whole class so that the other method can use it.

I designed it this way because the extra module might not be available for import in some cases. do_thing gets called quite frequently, so I'm hoping that it's possible to avoid putting the import statement there. Is there an easier way to do this that I'm missing?

3
  • It's hard to say with no knowledge of what extra does or what it returns. What particular functionality is important for the class Foo? Commented Dec 12, 2019 at 5:37
  • The current approach is working, right? Commented Dec 12, 2019 at 5:39
  • No, the current approach gives me the error NameError: extra is not defined when I run foo = Foo(True); foo.do_thing(). The problem that I am trying to fix is that the import statement is in the scope of the __init__ method, but I want the import to be usable for the whole class after initializing it. Commented Dec 12, 2019 at 21:56

1 Answer 1

3

I found a solution to my problem:

from importlib import import_module

class Foo:
    import_os = False
    os = None
    def __init__(self, imp):
        if imp:
            self.import_os = True
            self.os = import_module('os')
    def do_thing(self):
            print("doing thing")
            if self.import_os:
                print(self.os.devnull) # to verify that os has been imported

# check that it does actually work
print("running foo(false)")
f1=Foo(False)
f1.do_thing()
f2=Foo(True)
print("running foo(true)")
f2.do_thing()

It outputs

running foo(false)
doing thing
running foo(true)
doing thing
/dev/null

which is exactly the functionality that I want.

Here I'm using os instead of extra so that anyone can run it. These answers helped me figure it out:

Sign up to request clarification or add additional context in comments.

Comments

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.