Oleg Melnikov
Oleg Melnikov

Reputation: 3298

Efficient way to import libraries for class methods, in Python

What is the python and efficient way of importing libraries that are used throughout class's methods.

Module-level import is:

from numpy import exp

class A:
    def calc1(self): return exp(1)
    def calc2(self): return exp(1)

Method-level import is cleaner, but I'm not sure if library is cached or imported every time a method is called:

class B:
    def calc1(self):
        from numpy import exp
        return exp(1)

    def calc2(self):
        from numpy import exp
        return exp(1)

Finally, is there some class-level import as following?

class C:
    from numpy import exp
    def calc1(self): return exp(1)
    def calc2(self): return exp(1)

C().calc1()   # NameError: name 'exp' is not defined

Upvotes: 0

Views: 453

Answers (1)

Ben Kraft
Ben Kraft

Reputation: 494

I believe you can do class-level import, but you'll have to then call it as self.exp instead of just exp, since the imported name will be a class variable. But I think in general module-level import is simpler and should be preferred unless you have a specific reason to do otherwise (e.g., circular imports or imports that won't always be available).

Upvotes: 2

Related Questions