Brindha
Brindha

Reputation: 359

Different Import statements for different classes in same .py file?

In Python, I have seen that the practice of multiple classes in the same module or .py file is prevalent. But if the different classes use entirely different packages, is it possible to selectively specify import statements for the classes?

Is the following(or some variation) possible?

samefile.py:

import foo1
import foo2
class one
       ....
import foo2
import foo3
class two
       ....

Also, I saw that modules can be imported dynamically using importlib module, imp module, etc. but they require knowledge of the path to the modules, so I'm queasy about trying those.

My classes are closely related, which means it would be useful if they were in the same .py file (for simplicity's sake). However, they also use entirely different modules by import.

Is there a way to do this? Just wanted to know so that if not, I will have to resort to individual .py files for each class.

Upvotes: 0

Views: 65

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50116

This is perfectly possible:

import collections
class Foobar(collections.OrderedDict):
  pass

import weakref
class Barfoo(weakref.WeakKeyDictionary):
  pass

For readability, you should have your imports at the top of a file. Sometimes, delayed imports may be necessary to avoid circular dependencies, however.

Upvotes: 1

Related Questions