Can anyone suggest me what is the most pythonic way to import modules in python? Let me explain - i have read a lot of python code and found several different ways of how to import modules or if to be more precise - when to import:
Please find samples below.
#references.py
import re
import clr
import math
import System
import System.Text.RegularExpressions
import System.Random
import System.Threading
import System.DateTime
# System assemblies
clr.AddReference("System.Core")
clr.AddReference("System.Data")
clr.AddReference("System.Drawing")
...
#test.py
from references.syslibs import (Array, DataTable, OleDbConnection, OleDbDataAdapter,
OleDbCommand, OleDbSchemaGuid)
def get_dict_from_data_table(dataTable):
pass
from ... import ...
from ... import ...
def Generate(param, param1 ...):
pass
import clr
clr.AddReference("assembly")
from ... import ...
...
def generate_(txt, param1, param2):
from ... import ...
from ... import ...
from ... import ...
if not cond(param1): res = "text"
if not cond(param2): name = "default"
So what is the most pythonic way to import modules in python?
It really doesn't matter, so long as you don't from ... import *
. The rest is all taste and getting around cyclic import issues. PEP 8 states that you should import at the top of the script, but even that isn't set in stone.
People have already commented on the major style issues (at the top of the script, etc), so I'll skip that.
For my imports, I usually have them ordered alphabetically by module name (regardless of whether it's 'import' or 'from ... import ...'. I split it into groups of: standard lib; third party modules (from pypi or other); internal modules.
import os
import system
import twisted
import zope
import mymodule_1
import mymodule_2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With