Aquí es una respuesta 2014 a una pregunta 2011 -
El autor de isort, una herramienta que limpia las importaciones, tuvo que lidiar este mismo problema con el fin de satisfacer el requisito PEP8 que las importaciones base de la biblioteca deben ser solicitados antes importaciones de terceros.
He estado usando esta herramienta y parece estar funcionando bien. Usted puede utilizar el método place_module
en el archivo isort.py
, ya que es de código abierto espero que el autor no le importaría que me reproduce la lógica aquí:
def place_module(self, moduleName):
"""Tries to determine if a module is a python std import, third party import, or project code:
if it can't determine - it assumes it is project code
"""
if moduleName.startswith("."):
return SECTIONS.LOCALFOLDER
index = moduleName.find('.')
if index:
firstPart = moduleName[:index]
else:
firstPart = None
for forced_separate in self.config['forced_separate']:
if moduleName.startswith(forced_separate):
return forced_separate
if moduleName == "__future__" or (firstPart == "__future__"):
return SECTIONS.FUTURE
elif moduleName in self.config['known_standard_library'] or \
(firstPart in self.config['known_standard_library']):
return SECTIONS.STDLIB
elif moduleName in self.config['known_third_party'] or (firstPart in self.config['known_third_party']):
return SECTIONS.THIRDPARTY
elif moduleName in self.config['known_first_party'] or (firstPart in self.config['known_first_party']):
return SECTIONS.FIRSTPARTY
for prefix in PYTHONPATH:
module_path = "/".join((prefix, moduleName.replace(".", "/")))
package_path = "/".join((prefix, moduleName.split(".")[0]))
if (os.path.exists(module_path + ".py") or os.path.exists(module_path + ".so") or
(os.path.exists(package_path) and os.path.isdir(package_path))):
if "site-packages" in prefix or "dist-packages" in prefix:
return SECTIONS.THIRDPARTY
elif "python2" in prefix.lower() or "python3" in prefix.lower():
return SECTIONS.STDLIB
else:
return SECTIONS.FIRSTPARTY
return SECTION_NAMES.index(self.config['default_section'])
Obviamente es necesario utilizar este método en el contexto de la clase y la archivo de configuración Eso es básicamente una alternativa en una lista estática de importaciones conocidas de lib core.
# Note that none of these lists must be complete as they are simply fallbacks for when included auto-detection fails.
default = {'force_to_top': [],
'skip': ['__init__.py', ],
'line_length': 80,
'known_standard_library': ["abc", "anydbm", "argparse", "array", "asynchat", "asyncore", "atexit", "base64",
"BaseHTTPServer", "bisect", "bz2", "calendar", "cgitb", "cmd", "codecs",
"collections", "commands", "compileall", "ConfigParser", "contextlib", "Cookie",
"copy", "cPickle", "cProfile", "cStringIO", "csv", "datetime", "dbhash", "dbm",
"decimal", "difflib", "dircache", "dis", "doctest", "dumbdbm", "EasyDialogs",
"errno", "exceptions", "filecmp", "fileinput", "fnmatch", "fractions",
"functools", "gc", "gdbm", "getopt", "getpass", "gettext", "glob", "grp", "gzip",
"hashlib", "heapq", "hmac", "imaplib", "imp", "inspect", "itertools", "json",
"linecache", "locale", "logging", "mailbox", "math", "mhlib", "mmap",
"multiprocessing", "operator", "optparse", "os", "pdb", "pickle", "pipes",
"pkgutil", "platform", "plistlib", "pprint", "profile", "pstats", "pwd", "pyclbr",
"pydoc", "Queue", "random", "re", "readline", "resource", "rlcompleter",
"robotparser", "sched", "select", "shelve", "shlex", "shutil", "signal",
"SimpleXMLRPCServer", "site", "sitecustomize", "smtpd", "smtplib", "socket",
"SocketServer", "sqlite3", "string", "StringIO", "struct", "subprocess", "sys",
"sysconfig", "tabnanny", "tarfile", "tempfile", "textwrap", "threading", "time",
"timeit", "trace", "traceback", "unittest", "urllib", "urllib2", "urlparse",
"usercustomize", "uuid", "warnings", "weakref", "webbrowser", "whichdb", "xml",
"xmlrpclib", "zipfile", "zipimport", "zlib", 'builtins', '__builtin__'],
'known_third_party': ['google.appengine.api'],
'known_first_party': [],
--- --- cortar
que ya era una hora en la escritura de esta herramienta para mí antes de que me encontré con el módulo iSort, así que espero que esto también puede ayudar a alguien más para evitar la re-inventar ¡la rueda!
Este es un duplicado aproximada de http://stackoverflow.com/questions/5632980/list-of-all-imports-in- python-3, que desafortunadamente no atrajo ninguna respuesta particularmente útil hasta el momento. –