简体   繁体   English

在python中从导入中导入导入

[英]importing imports from your imports in python

Question: In python, Is it wise to use the imports from your sub classes, or does it matter? 问题:在python中,使用子类中的导入是否明智?


Info: 信息:

So, I have a program split up over 6 files. 因此,我有一个程序,分为6个文件。 in almost every one of the .py files i import threading, socket, and pickle. 在几乎每个.py文件中,我都导入了线程,套接字和pickle。 What I'm wondering is this, is there an efficiency difference between: 我想知道的是,两者之间是否存在效率差异?

File1.py: File1.py:

import socket

File2.py: File2.py:

import File1
import socket

and this: 和这个:

File2.py: File2.py:

import File1
from File1 import socket

Or even this: 甚至这个:

File2.py File2.py

import File1
socket = File1.socket

Don't use from File1 import socket . 不要from File1 import socket It doesn't make a performance difference, but it gives headaches to other people having to look in the other file to see that File1.socket is actually socket , and it might get messy if you decide you don't need socket in File1 . 这是没有的性能差异,但它给头疼不必看在其他文件中看到,其他人File1.socket实际上是socket ,如果你决定你不需要它可能会导致混乱socketFile1

Also, this is against the python principles because: 另外,这违反了python原理,因为:

  1. it's not the obvious way to do it 这不是显而易见的方法
  2. flat is better than nested 平比嵌套好
  3. readability counts 可读性计数
  4. special cases aren't special enough to break the rules 特殊情况不足以违反规则

The import statement is smart enough to realize when a module has already been imported, an not import it again. import语句足够聪明,可以知道何时已导入模块,而无需再次导入。 So: 所以:

File.py: File.py:

import socket

File2.py: File2.py:

import File1
import socket

is just fine. 很好

No, there is no efficiency difference. 不,没有效率差异。 The first approach is the best, since it promotes modularity (like for instance, what if File1.py decides to stop importing socket , then File2.py gets broken) 第一种方法是最好的,因为它促进了模块化(例如,如果File1.py决定停止导入socket ,那么File2.py会崩溃)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM