Home > front end >  What better way? import module that import module or import 2 modules? [closed]
What better way? import module that import module or import 2 modules? [closed]

Time:09-29

file3.py:

import file2


bc = file2.BirthdayCard()
bc.greeting_msg()

#file1 import file2
#BirthdayCard in file2 is subclass of GreetingCard in file1
gc = file2.file1.GreetingCard()
gc.greeting_msg()

or:

file3.py:

import file2
import file1


bc = file2.BirthdayCard()
bc.greeting_msg()

gc = file1.GreetingCard()
gc.greeting_msg()

It seems that in the second way I take up more memory for importing again file1 although it already imported in file2 and I could use him as I did in the first way

CodePudding user response:

Relying on the other file file2 that it will always import file1 would obviously fail if file2 was refactored to not depend on file1. Imagine that scenario where we removed import file1 from file2 and then file3 was affected :) Now, it would be very unexpected that such change in file2 (let's say even if it doesn't change any of the functionalities it exports to other files) would result to all those other files that uses it to be changed as well even if they shouldn't be.

Also, explicitly importing file2 and file1 clearly indicates that the file depends on both modules, no hidden surprises here.

Most of the time, you should only be importing what you need and not necessarily the whole module (case-to-case basis).

from file1 import GreetingCard
from file2 import BirthdayCard

Even PEP8 suggests the usage of absolute imports. Obviously, file2.file1 doesn't make sense from that perspective (even with explicit relative imports) as it should just be file1.

CodePudding user response:

file2 permanently imports file1. Therefore there will be an error.We need to refactor file2 so it doesn't depend on file1.

  • Related