index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
722,933 |
gitdb.db.pack
|
store
|
Storing individual objects is not feasible as a pack is designed to
hold multiple objects. Writing or rewriting packs for single objects is
inefficient
|
def store(self, istream):
"""Storing individual objects is not feasible as a pack is designed to
hold multiple objects. Writing or rewriting packs for single objects is
inefficient"""
raise UnsupportedOperation()
|
(self, istream)
|
722,934 |
gitdb.db.pack
|
stream
| null |
def stream(self, sha):
entity, index = self._pack_info(sha)
return entity.stream_at_index(index)
|
(self, sha)
|
722,935 |
gitdb.db.pack
|
update_cache
|
Update our cache with the actually existing packs on disk. Add new ones,
and remove deleted ones. We keep the unchanged ones
:param force: If True, the cache will be updated even though the directory
does not appear to have changed according to its modification timestamp.
:return: True if the packs have been updated so there is new information,
False if there was no change to the pack database
|
def update_cache(self, force=False):
"""
Update our cache with the actually existing packs on disk. Add new ones,
and remove deleted ones. We keep the unchanged ones
:param force: If True, the cache will be updated even though the directory
does not appear to have changed according to its modification timestamp.
:return: True if the packs have been updated so there is new information,
False if there was no change to the pack database"""
stat = os.stat(self.root_path())
if not force and stat.st_mtime <= self._st_mtime:
return False
# END abort early on no change
self._st_mtime = stat.st_mtime
# packs are supposed to be prefixed with pack- by git-convention
# get all pack files, figure out what changed
pack_files = set(glob.glob(os.path.join(self.root_path(), "pack-*.pack")))
our_pack_files = {item[1].pack().path() for item in self._entities}
# new packs
for pack_file in (pack_files - our_pack_files):
# init the hit-counter/priority with the size, a good measure for hit-
# probability. Its implemented so that only 12 bytes will be read
entity = PackEntity(pack_file)
self._entities.append([entity.pack().size(), entity, entity.index().sha_to_index])
# END for each new packfile
# removed packs
for pack_file in (our_pack_files - pack_files):
del_index = -1
for i, item in enumerate(self._entities):
if item[1].pack().path() == pack_file:
del_index = i
break
# END found index
# END for each entity
assert del_index != -1
del(self._entities[del_index])
# END for each removed pack
# reinitialize prioritiess
self._sort_entities()
return True
|
(self, force=False)
|
722,936 |
gitdb.db.ref
|
ReferenceDB
|
A database consisting of database referred to in a file
|
class ReferenceDB(CompoundDB):
"""A database consisting of database referred to in a file"""
# Configuration
# Specifies the object database to use for the paths found in the alternates
# file. If None, it defaults to the GitDB
ObjectDBCls = None
def __init__(self, ref_file):
super().__init__()
self._ref_file = ref_file
def _set_cache_(self, attr):
if attr == '_dbs':
self._dbs = list()
self._update_dbs_from_ref_file()
else:
super()._set_cache_(attr)
# END handle attrs
def _update_dbs_from_ref_file(self):
dbcls = self.ObjectDBCls
if dbcls is None:
# late import
from gitdb.db.git import GitDB
dbcls = GitDB
# END get db type
# try to get as many as possible, don't fail if some are unavailable
ref_paths = list()
try:
with codecs.open(self._ref_file, 'r', encoding="utf-8") as f:
ref_paths = [l.strip() for l in f]
except OSError:
pass
# END handle alternates
ref_paths_set = set(ref_paths)
cur_ref_paths_set = {db.root_path() for db in self._dbs}
# remove existing
for path in (cur_ref_paths_set - ref_paths_set):
for i, db in enumerate(self._dbs[:]):
if db.root_path() == path:
del(self._dbs[i])
continue
# END del matching db
# END for each path to remove
# add new
# sort them to maintain order
added_paths = sorted(ref_paths_set - cur_ref_paths_set, key=lambda p: ref_paths.index(p))
for path in added_paths:
try:
db = dbcls(path)
# force an update to verify path
if isinstance(db, CompoundDB):
db.databases()
# END verification
self._dbs.append(db)
except Exception:
# ignore invalid paths or issues
pass
# END for each path to add
def update_cache(self, force=False):
# re-read alternates and update databases
self._update_dbs_from_ref_file()
return super().update_cache(force)
|
(ref_file)
|
722,939 |
gitdb.db.ref
|
__init__
| null |
def __init__(self, ref_file):
super().__init__()
self._ref_file = ref_file
|
(self, ref_file)
|
722,941 |
gitdb.db.ref
|
_set_cache_
| null |
def _set_cache_(self, attr):
if attr == '_dbs':
self._dbs = list()
self._update_dbs_from_ref_file()
else:
super()._set_cache_(attr)
# END handle attrs
|
(self, attr)
|
722,942 |
gitdb.db.ref
|
_update_dbs_from_ref_file
| null |
def _update_dbs_from_ref_file(self):
dbcls = self.ObjectDBCls
if dbcls is None:
# late import
from gitdb.db.git import GitDB
dbcls = GitDB
# END get db type
# try to get as many as possible, don't fail if some are unavailable
ref_paths = list()
try:
with codecs.open(self._ref_file, 'r', encoding="utf-8") as f:
ref_paths = [l.strip() for l in f]
except OSError:
pass
# END handle alternates
ref_paths_set = set(ref_paths)
cur_ref_paths_set = {db.root_path() for db in self._dbs}
# remove existing
for path in (cur_ref_paths_set - ref_paths_set):
for i, db in enumerate(self._dbs[:]):
if db.root_path() == path:
del(self._dbs[i])
continue
# END del matching db
# END for each path to remove
# add new
# sort them to maintain order
added_paths = sorted(ref_paths_set - cur_ref_paths_set, key=lambda p: ref_paths.index(p))
for path in added_paths:
try:
db = dbcls(path)
# force an update to verify path
if isinstance(db, CompoundDB):
db.databases()
# END verification
self._dbs.append(db)
except Exception:
# ignore invalid paths or issues
pass
# END for each path to add
|
(self)
|
722,950 |
gitdb.db.ref
|
update_cache
| null |
def update_cache(self, force=False):
# re-read alternates and update databases
self._update_dbs_from_ref_file()
return super().update_cache(force)
|
(self, force=False)
|
722,951 |
gitdb.stream
|
Sha1Writer
|
Simple stream writer which produces a sha whenever you like as it degests
everything it is supposed to write
|
class Sha1Writer:
"""Simple stream writer which produces a sha whenever you like as it degests
everything it is supposed to write"""
__slots__ = "sha1"
def __init__(self):
self.sha1 = make_sha()
#{ Stream Interface
def write(self, data):
""":raise IOError: If not all bytes could be written
:param data: byte object
:return: length of incoming data"""
self.sha1.update(data)
return len(data)
# END stream interface
#{ Interface
def sha(self, as_hex=False):
""":return: sha so far
:param as_hex: if True, sha will be hex-encoded, binary otherwise"""
if as_hex:
return self.sha1.hexdigest()
return self.sha1.digest()
#} END interface
|
()
|
722,952 |
gitdb.stream
|
__init__
| null |
def __init__(self):
self.sha1 = make_sha()
|
(self)
|
722,954 |
gitdb.stream
|
write
|
:raise IOError: If not all bytes could be written
:param data: byte object
:return: length of incoming data
|
def write(self, data):
""":raise IOError: If not all bytes could be written
:param data: byte object
:return: length of incoming data"""
self.sha1.update(data)
return len(data)
|
(self, data)
|
722,955 |
gitdb.stream
|
ZippedStoreShaWriter
|
Remembers everything someone writes to it and generates a sha
|
class ZippedStoreShaWriter(Sha1Writer):
"""Remembers everything someone writes to it and generates a sha"""
__slots__ = ('buf', 'zip')
def __init__(self):
Sha1Writer.__init__(self)
self.buf = BytesIO()
self.zip = zlib.compressobj(zlib.Z_BEST_SPEED)
def __getattr__(self, attr):
return getattr(self.buf, attr)
def write(self, data):
alen = Sha1Writer.write(self, data)
self.buf.write(self.zip.compress(data))
return alen
def close(self):
self.buf.write(self.zip.flush())
def seek(self, offset, whence=getattr(os, 'SEEK_SET', 0)):
"""Seeking currently only supports to rewind written data
Multiple writes are not supported"""
if offset != 0 or whence != getattr(os, 'SEEK_SET', 0):
raise ValueError("Can only seek to position 0")
# END handle offset
self.buf.seek(0)
def getvalue(self):
""":return: string value from the current stream position to the end"""
return self.buf.getvalue()
|
()
|
722,956 |
gitdb.stream
|
__getattr__
| null |
def __getattr__(self, attr):
return getattr(self.buf, attr)
|
(self, attr)
|
722,957 |
gitdb.stream
|
__init__
| null |
def __init__(self):
Sha1Writer.__init__(self)
self.buf = BytesIO()
self.zip = zlib.compressobj(zlib.Z_BEST_SPEED)
|
(self)
|
722,958 |
gitdb.stream
|
close
| null |
def close(self):
self.buf.write(self.zip.flush())
|
(self)
|
722,959 |
gitdb.stream
|
getvalue
|
:return: string value from the current stream position to the end
|
def getvalue(self):
""":return: string value from the current stream position to the end"""
return self.buf.getvalue()
|
(self)
|
722,960 |
gitdb.stream
|
seek
|
Seeking currently only supports to rewind written data
Multiple writes are not supported
|
def seek(self, offset, whence=getattr(os, 'SEEK_SET', 0)):
"""Seeking currently only supports to rewind written data
Multiple writes are not supported"""
if offset != 0 or whence != getattr(os, 'SEEK_SET', 0):
raise ValueError("Can only seek to position 0")
# END handle offset
self.buf.seek(0)
|
(self, offset, whence=0)
|
722,962 |
gitdb.stream
|
write
| null |
def write(self, data):
alen = Sha1Writer.write(self, data)
self.buf.write(self.zip.compress(data))
return alen
|
(self, data)
|
722,963 |
gitdb
|
_init_externals
|
Initialize external projects by putting them into the path
|
def _init_externals():
"""Initialize external projects by putting them into the path"""
if 'PYOXIDIZER' not in os.environ:
where = os.path.join(os.path.dirname(__file__), 'ext', 'smmap')
if os.path.exists(where):
sys.path.append(where)
import smmap
del smmap
# END handle imports
|
()
|
722,980 |
pyopenstates.core
|
APIError
|
Raised when the Open States API returns an error
|
class APIError(RuntimeError):
"""
Raised when the Open States API returns an error
"""
pass
| null |
722,981 |
pyopenstates.core
|
NotFound
|
Raised when the API cannot find the requested object
|
class NotFound(APIError):
"""Raised when the API cannot find the requested object"""
pass
| null |
722,984 |
pyopenstates.core
|
get_bill
|
Returns details of a specific bill Can be identified by the Open States
unique bill id (uid), or by specifying the state, session, and
legislative bill ID
Args:
uid: The Open States unique bill ID
state: The postal code of the state
session: The legislative session (see state metadata)
bill_id: Yhe legislative bill ID (e.g. ``HR 42``)
**kwargs: Optional keyword argument options, such as ``fields``,
which specifies the fields to return
Returns:
The :ref:`Bill` details as a dictionary
|
def get_bill(uid=None, state=None, session=None, bill_id=None, include=None):
"""
Returns details of a specific bill Can be identified by the Open States
unique bill id (uid), or by specifying the state, session, and
legislative bill ID
Args:
uid: The Open States unique bill ID
state: The postal code of the state
session: The legislative session (see state metadata)
bill_id: Yhe legislative bill ID (e.g. ``HR 42``)
**kwargs: Optional keyword argument options, such as ``fields``,
which specifies the fields to return
Returns:
The :ref:`Bill` details as a dictionary
"""
args = {"include": include} if include else {}
if uid:
if state or session or bill_id:
raise ValueError(
"Must specify an Open States bill (uid), or the "
"state, session, and bill ID"
)
uid = _fix_id_string("ocd-bill/", uid)
return _get(f"bills/{uid}", params=args)
else:
if not state or not session or not bill_id:
raise ValueError(
"Must specify an Open States bill (uid), "
"or the state, session, and bill ID"
)
return _get(f"bills/{state.lower()}/{session}/{bill_id}", params=args)
|
(uid=None, state=None, session=None, bill_id=None, include=None)
|
722,985 |
pyopenstates.core
|
get_legislator
|
Gets a legislator's details
Args:
leg_id: The Legislator's Open States ID
fields: An optional custom list of fields to return
Returns:
The requested :ref:`Legislator` details as a dictionary
|
def get_legislator(leg_id):
"""
Gets a legislator's details
Args:
leg_id: The Legislator's Open States ID
fields: An optional custom list of fields to return
Returns:
The requested :ref:`Legislator` details as a dictionary
"""
leg_id = _fix_id_string("ocd-person/", leg_id)
return _get("people/", params={"id": [leg_id]})["results"][0]
|
(leg_id)
|
722,986 |
pyopenstates.core
|
get_metadata
|
Returns a list of all states with data available, and basic metadata
about their status. Can also get detailed metadata for a particular
state.
Args:
state: The abbreviation of state to get detailed metadata on, or leave
as None to get high-level metadata on all states.
include: Additional includes.
fields: An optional list of fields to return; returns all fields by
default
Returns:
Dict: The requested :ref:`Metadata` as a dictionary
|
def get_metadata(state=None, include=None, fields=None):
"""
Returns a list of all states with data available, and basic metadata
about their status. Can also get detailed metadata for a particular
state.
Args:
state: The abbreviation of state to get detailed metadata on, or leave
as None to get high-level metadata on all states.
include: Additional includes.
fields: An optional list of fields to return; returns all fields by
default
Returns:
Dict: The requested :ref:`Metadata` as a dictionary
"""
uri = "jurisdictions"
params = dict()
if include:
params["include"] = _include_list(include)
if state:
uri += "/" + _jurisdiction_id(state)
state_response = _get(uri, params=params)
if fields is not None:
return {k: state_response[k] for k in fields}
else:
return state_response
else:
params["page"] = "1"
params["per_page"] = "52"
return _get(uri, params=params)["results"]
|
(state=None, include=None, fields=None)
|
722,987 |
pyopenstates.core
|
get_organizations
| null |
def get_organizations(state):
uri = "jurisdictions"
uri += "/" + _jurisdiction_id(state)
state_response = _get(uri, params={"include": "organizations"})
return state_response["organizations"]
|
(state)
|
722,988 |
pyopenstates.core
|
locate_legislators
|
Returns a list of legislators for the given latitude/longitude coordinates
Args:
lat: Latitude
long: Longitude
fields: An optional custom list of fields to return
Returns:
A list of matching :ref:`Legislator` dictionaries
|
def locate_legislators(lat, lng, fields=None):
"""
Returns a list of legislators for the given latitude/longitude coordinates
Args:
lat: Latitude
long: Longitude
fields: An optional custom list of fields to return
Returns:
A list of matching :ref:`Legislator` dictionaries
"""
return _get(
"people.geo/", params=dict(lat=float(lat), lng=float(lng), fields=fields)
)["results"]
|
(lat, lng, fields=None)
|
722,989 |
pyopenstates.core
|
search_bills
|
Find bills matching a given set of filters
For a list of each field, example values, etc. see
https://v3.openstates.org/docs#/bills/bills_search_bills_get
|
def search_bills(
jurisdiction=None,
identifier=None,
session=None,
chamber=None,
classification=None,
subject=None,
updated_since=None,
created_since=None,
action_since=None,
sponsor=None,
sponsor_classification=None,
q=None,
# control params
sort=None,
include=None,
page=1,
per_page=10,
all_pages=True,
# alternate names for other parameters
state=None,
):
"""
Find bills matching a given set of filters
For a list of each field, example values, etc. see
https://v3.openstates.org/docs#/bills/bills_search_bills_get
"""
uri = "bills/"
args = {}
jurisdiction = _alt_parameter(state, jurisdiction, "state", "jurisdiction")
if jurisdiction:
args["jurisdiction"] = jurisdiction
if session:
args["session"] = session
if chamber:
args["chamber"] = chamber
if classification:
args["classification"] = classification
if subject:
args["subject"] = subject
if updated_since:
args["updated_since"] = updated_since
if created_since:
args["created_since"] = created_since
if action_since:
args["action_since"] = action_since
if sponsor:
args["sponsor"] = sponsor
if sponsor_classification:
args["sponsor_classification"] = sponsor_classification
if q:
args["q"] = q
if sort:
args["sort"] = sort
if include:
args["include"] = include
results = []
if all_pages:
args["per_page"] = 20
args["page"] = 1
else:
args["per_page"] = per_page
args["page"] = page
resp = _get(uri, params=args)
results += resp["results"]
if all_pages:
while resp["pagination"]["page"] < resp["pagination"]["max_page"]:
args["page"] += 1
sleep(1)
resp = _get(uri, params=args)
results += resp["results"]
return results
|
(jurisdiction=None, identifier=None, session=None, chamber=None, classification=None, subject=None, updated_since=None, created_since=None, action_since=None, sponsor=None, sponsor_classification=None, q=None, sort=None, include=None, page=1, per_page=10, all_pages=True, state=None)
|
722,990 |
pyopenstates.core
|
search_districts
|
Search for districts
Args:
state: The state to search in
chamber: the upper or lower legislative chamber
fields: Optionally specify a custom list of fields to return
Returns:
A list of matching :ref:`District` dictionaries
|
def search_districts(state, chamber):
"""
Search for districts
Args:
state: The state to search in
chamber: the upper or lower legislative chamber
fields: Optionally specify a custom list of fields to return
Returns:
A list of matching :ref:`District` dictionaries
"""
if chamber:
chamber = chamber.lower()
if chamber not in ["upper", "lower"]:
raise ValueError('Chamber must be "upper" or "lower"')
organizations = get_organizations(state=state)
for org in organizations:
if org["classification"] == chamber:
return org["districts"]
|
(state, chamber)
|
722,991 |
pyopenstates.core
|
search_legislators
|
Search for legislators.
Returns:
A list of matching :ref:`Legislator` dictionaries
|
def search_legislators(
jurisdiction=None,
name=None,
id_=None,
org_classification=None,
district=None,
include=None,
):
"""
Search for legislators.
Returns:
A list of matching :ref:`Legislator` dictionaries
"""
params = _make_params(
jurisdiction=jurisdiction,
name=name,
id=id_,
org_classification=org_classification,
district=district,
include=include,
)
return _get("people", params)["results"]
|
(jurisdiction=None, name=None, id_=None, org_classification=None, district=None, include=None)
|
722,992 |
pyopenstates.core
|
set_api_key
|
Sets API key. Can also be set as OPENSTATES_API_KEY environment
variable.
|
def set_api_key(apikey):
"""Sets API key. Can also be set as OPENSTATES_API_KEY environment
variable."""
session.headers["X-Api-Key"] = apikey
|
(apikey)
|
722,993 |
pyopenstates.core
|
set_user_agent
|
Appends a custom string to the default User-Agent string
(e.g. ``pyopenstates/__version__ user_agent``)
|
def set_user_agent(user_agent):
"""Appends a custom string to the default User-Agent string
(e.g. ``pyopenstates/__version__ user_agent``)"""
session.headers.update({"User-Agent": f"{DEFAULT_USER_AGENT} {user_agent}"})
|
(user_agent)
|
722,994 |
pyvat.item_type
|
ItemType
|
Item type.
If no item type matches the type of item being sold, it is currently not
supported by pyvat.
|
class ItemType(Enum):
"""Item type.
If no item type matches the type of item being sold, it is currently not
supported by pyvat.
"""
generic_physical_good = 1
"""Generic physical good.
"""
generic_electronic_service = 2
"""Generic electronic service.
Any electronic service that is not covered by a more specific item type.
"""
generic_telecommunications_service = 3
"""Generic telecommunications service.
Any telecommunications service that is not covered by a more specific item
type.
"""
generic_broadcasting_service = 4
"""Generic broadcasting service.
Any broadcasting service that is not covered by a more specific item type.
"""
prepaid_broadcasting_service = 5
"""Pre-paid service provided by broadcasting company.
"""
ebook = 6
"""E-book.
"""
enewspaper = 7
"""E-newspaper.
"""
@property
def is_electronic_service(self):
return self in frozenset([ItemType.generic_electronic_service,
ItemType.ebook,
ItemType.enewspaper])
@property
def is_telecommunications_service(self):
return self in frozenset([ItemType.generic_telecommunications_service])
@property
def is_broadcasting_service(self):
return self in frozenset([ItemType.generic_broadcasting_service,
ItemType.prepaid_broadcasting_service])
|
(value, names=None, *, module=None, qualname=None, type=None, start=1)
|
722,995 |
pyvat.party
|
Party
|
Trading party.
Represents either a consumer or business in a given country acting as a
party to a transaction.
:ivar country_code:
Party's legal or effective country of registration or residence as an
ISO 3166-1 alpha-2 country code.
:type country_code: str
:ivar is_business: Whether the part is a legal business entity.
:type is_business: bool
|
class Party(object):
"""Trading party.
Represents either a consumer or business in a given country acting as a
party to a transaction.
:ivar country_code:
Party's legal or effective country of registration or residence as an
ISO 3166-1 alpha-2 country code.
:type country_code: str
:ivar is_business: Whether the part is a legal business entity.
:type is_business: bool
"""
def __init__(self, country_code, is_business):
"""Initialize a trading party.
:param country_code:
Party's legal or effective country of registration or residence as
an ISO 3166-1 alpha-2 country code.
:type country_code: str
:param is_business: Whether the part is a legal business entity.
:type is_business: bool
"""
self.country_code = country_code
self.is_business = is_business
def __repr__(self):
return '<pyvat.Party: country code = %s, is business = %r>' % (
self.country_code, self.is_business,
)
|
(country_code, is_business)
|
722,996 |
pyvat.party
|
__init__
|
Initialize a trading party.
:param country_code:
Party's legal or effective country of registration or residence as
an ISO 3166-1 alpha-2 country code.
:type country_code: str
:param is_business: Whether the part is a legal business entity.
:type is_business: bool
|
def __init__(self, country_code, is_business):
"""Initialize a trading party.
:param country_code:
Party's legal or effective country of registration or residence as
an ISO 3166-1 alpha-2 country code.
:type country_code: str
:param is_business: Whether the part is a legal business entity.
:type is_business: bool
"""
self.country_code = country_code
self.is_business = is_business
|
(self, country_code, is_business)
|
722,997 |
pyvat.party
|
__repr__
| null |
def __repr__(self):
return '<pyvat.Party: country code = %s, is business = %r>' % (
self.country_code, self.is_business,
)
|
(self)
|
722,998 |
pyvat.vat_charge
|
VatCharge
|
VAT charge.
:ivar action: VAT charge action.
:type action: VatChargeAction
:ivar country_code:
Country in which the action applies as the ISO 3166-1 alpha-2 code of
the country.
:type country_code: str
:ivar rate:
VAT rate in percent. I.e. a value of 25 indicates a VAT charge of 25 %.
:type rate: Decimal
|
class VatCharge(object):
"""VAT charge.
:ivar action: VAT charge action.
:type action: VatChargeAction
:ivar country_code:
Country in which the action applies as the ISO 3166-1 alpha-2 code of
the country.
:type country_code: str
:ivar rate:
VAT rate in percent. I.e. a value of 25 indicates a VAT charge of 25 %.
:type rate: Decimal
"""
def __init__(self, action, country_code, rate):
self.action = action
self.country_code = country_code
self.rate = ensure_decimal(rate)
def __repr__(self):
return '<%s.%s: action = %r, country code = %r, rate = %s>' % (
self.__class__.__module__,
self.__class__.__name__,
self.action,
self.country_code,
self.rate,
)
|
(action, country_code, rate)
|
722,999 |
pyvat.vat_charge
|
__init__
| null |
def __init__(self, action, country_code, rate):
self.action = action
self.country_code = country_code
self.rate = ensure_decimal(rate)
|
(self, action, country_code, rate)
|
723,000 |
pyvat.vat_charge
|
__repr__
| null |
def __repr__(self):
return '<%s.%s: action = %r, country code = %r, rate = %s>' % (
self.__class__.__module__,
self.__class__.__name__,
self.action,
self.country_code,
self.rate,
)
|
(self)
|
723,001 |
pyvat.vat_charge
|
VatChargeAction
|
VAT charge action.
|
class VatChargeAction(Enum):
"""VAT charge action.
"""
charge = 1
"""Charge VAT.
"""
reverse_charge = 2
"""No VAT charged but customer is required to account via reverse-charge.
"""
no_charge = 3
"""No VAT charged.
"""
|
(value, names=None, *, module=None, qualname=None, type=None, start=1)
|
723,002 |
pyvat.result
|
VatNumberCheckResult
|
Result of a VAT number validation check.
:ivar is_valid:
Boolean value indicating if the checked VAT number was deemed to be
valid. ``True`` if the VAT number is valid or ``False`` if the VAT
number is positively invalid.
:ivar log_lines:
Check log lines.
:ivar business_name: Optional business name retrieved for the VAT number.
:ivar business_address: Optional address retrieved for the VAT number.
|
class VatNumberCheckResult(object):
"""Result of a VAT number validation check.
:ivar is_valid:
Boolean value indicating if the checked VAT number was deemed to be
valid. ``True`` if the VAT number is valid or ``False`` if the VAT
number is positively invalid.
:ivar log_lines:
Check log lines.
:ivar business_name: Optional business name retrieved for the VAT number.
:ivar business_address: Optional address retrieved for the VAT number.
"""
def __init__(self,
is_valid=None,
log_lines=None,
business_name=None,
business_address=None,
business_country_code=None):
self.is_valid = is_valid
self.log_lines = log_lines or []
self.business_name = business_name
self.business_address = business_address
self.business_country_code = business_country_code
|
(is_valid=None, log_lines=None, business_name=None, business_address=None, business_country_code=None)
|
723,003 |
pyvat.result
|
__init__
| null |
def __init__(self,
is_valid=None,
log_lines=None,
business_name=None,
business_address=None,
business_country_code=None):
self.is_valid = is_valid
self.log_lines = log_lines or []
self.business_name = business_name
self.business_address = business_address
self.business_country_code = business_country_code
|
(self, is_valid=None, log_lines=None, business_name=None, business_address=None, business_country_code=None)
|
723,004 |
pyvat.registries
|
ViesRegistry
|
VIES registry.
Uses the European Commision's VIES registry for validating VAT numbers.
|
class ViesRegistry(Registry):
"""VIES registry.
Uses the European Commision's VIES registry for validating VAT numbers.
"""
CHECK_VAT_SERVICE_URL = 'http://ec.europa.eu/taxation_customs/vies/' \
'services/checkVatService'
"""URL for the VAT checking service.
"""
DEFAULT_TIMEOUT = 8
"""Timeout for the requests."""
def check_vat_number(self, vat_number, country_code):
# Non-ISO code used for Greece.
if country_code == 'GR':
country_code = 'EL'
# Request information about the VAT number.
result = VatNumberCheckResult()
request_data = (
u'<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope'
u' xmlns:ns0="urn:ec.europa.eu:taxud:vies:services:checkVa'
u't:types" xmlns:ns1="http://schemas.xmlsoap.org/soap/enve'
u'lope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta'
u'nce" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/env'
u'elope/"><SOAP-ENV:Header/><ns1:Body><ns0:checkVat><ns0:c'
u'ountryCode>%s</ns0:countryCode><ns0:vatNumber>%s</ns0:va'
u'tNumber></ns0:checkVat></ns1:Body></SOAP-ENV:Envelope>' %
(country_code, vat_number)
)
result.log_lines += [
u'> POST %s with payload of content type text/xml, charset UTF-8:',
request_data,
]
try:
response = requests.post(
self.CHECK_VAT_SERVICE_URL,
data=request_data.encode('utf-8'),
headers={
'Content-Type': 'text/xml; charset=utf-8',
},
timeout=self.DEFAULT_TIMEOUT
)
except Timeout as e:
result.log_lines.append(u'< Request to EU VIEW registry timed out:'
u' {}'.format(e))
return result
except Exception as exception:
# Do not completely fail problematic requests.
result.log_lines.append(u'< Request failed with exception: %r' %
(exception))
return result
# Log response information.
result.log_lines += [
u'< Response with status %d of content type %s:' %
(response.status_code, response.headers['Content-Type']),
response.text,
]
# Do not completely fail problematic requests.
if response.status_code != 200 or \
not response.headers['Content-Type'].startswith('text/xml'):
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid response status code or MIME '
u'type')
return result
# Parse the DOM and validate as much as we can.
#
# We basically expect the result structure to be as follows,
# where the address and name nodes might be omitted.
#
# <env:Envelope
# xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
# <env:Header/>
# <env:Body>
# <ns2:checkVatResponse
# xmlns:ns2="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
# <ns2:countryCode>DE</ns2:countryCode>
# <ns2:vatNumber>812383453</ns2:vatNumber>
# <ns2:requestDate>2022-08-12+02:00</ns2:requestDate>
# <ns2:valid>true</ns2:valid>
# <ns2:name>---</ns2:name>
# <ns2:address>---</ns2:address>
# </ns2:checkVatResponse>
# </env:Body>
# </env:Envelope>
result_dom = xml.dom.minidom.parseString(response.text.encode('utf-8'))
envelope_node = result_dom.documentElement
if envelope_node.tagName != 'env:Envelope':
raise ValueError(
'expected response XML root element to be a SOAP envelope'
)
body_node = get_first_child_element(envelope_node, 'env:Body')
# Check for server errors
try:
error_node = get_first_child_element(body_node, 'env:Fault')
fault_strings = error_node.getElementsByTagName('faultstring')
fault_code = fault_strings[0].firstChild.nodeValue
raise ServerError(fault_code)
except NodeNotFoundError:
pass
try:
check_vat_response_node = get_first_child_element(
body_node,
'ns2:checkVatResponse'
)
valid_node = get_first_child_element(
check_vat_response_node,
'ns2:valid'
)
except Exception as e:
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid response body: %r' % (e))
return result
# Parse the validity of the business.
valid_text = get_text(valid_node)
if valid_text in frozenset(('true', 'false')):
result.is_valid = valid_text == 'true'
else:
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid validity field: %r' %
(valid_text))
# Parse the business name and address if possible.
try:
name_node = get_first_child_element(
check_vat_response_node,
'ns2:name'
)
result.business_name = get_text(name_node).strip() or None
except Exception:
pass
try:
address_node = get_first_child_element(
check_vat_response_node,
'ns2:address'
)
result.business_address = get_text(address_node).strip() or None
except Exception:
pass
# Parse the country code if possible.
try:
country_code_node = get_first_child_element(
check_vat_response_node,
'ns2:countryCode'
)
result.business_country_code = get_text(country_code_node).strip() or None
except Exception:
pass
return result
|
()
|
723,005 |
pyvat.registries
|
check_vat_number
| null |
def check_vat_number(self, vat_number, country_code):
# Non-ISO code used for Greece.
if country_code == 'GR':
country_code = 'EL'
# Request information about the VAT number.
result = VatNumberCheckResult()
request_data = (
u'<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope'
u' xmlns:ns0="urn:ec.europa.eu:taxud:vies:services:checkVa'
u't:types" xmlns:ns1="http://schemas.xmlsoap.org/soap/enve'
u'lope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta'
u'nce" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/env'
u'elope/"><SOAP-ENV:Header/><ns1:Body><ns0:checkVat><ns0:c'
u'ountryCode>%s</ns0:countryCode><ns0:vatNumber>%s</ns0:va'
u'tNumber></ns0:checkVat></ns1:Body></SOAP-ENV:Envelope>' %
(country_code, vat_number)
)
result.log_lines += [
u'> POST %s with payload of content type text/xml, charset UTF-8:',
request_data,
]
try:
response = requests.post(
self.CHECK_VAT_SERVICE_URL,
data=request_data.encode('utf-8'),
headers={
'Content-Type': 'text/xml; charset=utf-8',
},
timeout=self.DEFAULT_TIMEOUT
)
except Timeout as e:
result.log_lines.append(u'< Request to EU VIEW registry timed out:'
u' {}'.format(e))
return result
except Exception as exception:
# Do not completely fail problematic requests.
result.log_lines.append(u'< Request failed with exception: %r' %
(exception))
return result
# Log response information.
result.log_lines += [
u'< Response with status %d of content type %s:' %
(response.status_code, response.headers['Content-Type']),
response.text,
]
# Do not completely fail problematic requests.
if response.status_code != 200 or \
not response.headers['Content-Type'].startswith('text/xml'):
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid response status code or MIME '
u'type')
return result
# Parse the DOM and validate as much as we can.
#
# We basically expect the result structure to be as follows,
# where the address and name nodes might be omitted.
#
# <env:Envelope
# xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
# <env:Header/>
# <env:Body>
# <ns2:checkVatResponse
# xmlns:ns2="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
# <ns2:countryCode>DE</ns2:countryCode>
# <ns2:vatNumber>812383453</ns2:vatNumber>
# <ns2:requestDate>2022-08-12+02:00</ns2:requestDate>
# <ns2:valid>true</ns2:valid>
# <ns2:name>---</ns2:name>
# <ns2:address>---</ns2:address>
# </ns2:checkVatResponse>
# </env:Body>
# </env:Envelope>
result_dom = xml.dom.minidom.parseString(response.text.encode('utf-8'))
envelope_node = result_dom.documentElement
if envelope_node.tagName != 'env:Envelope':
raise ValueError(
'expected response XML root element to be a SOAP envelope'
)
body_node = get_first_child_element(envelope_node, 'env:Body')
# Check for server errors
try:
error_node = get_first_child_element(body_node, 'env:Fault')
fault_strings = error_node.getElementsByTagName('faultstring')
fault_code = fault_strings[0].firstChild.nodeValue
raise ServerError(fault_code)
except NodeNotFoundError:
pass
try:
check_vat_response_node = get_first_child_element(
body_node,
'ns2:checkVatResponse'
)
valid_node = get_first_child_element(
check_vat_response_node,
'ns2:valid'
)
except Exception as e:
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid response body: %r' % (e))
return result
# Parse the validity of the business.
valid_text = get_text(valid_node)
if valid_text in frozenset(('true', 'false')):
result.is_valid = valid_text == 'true'
else:
result.log_lines.append(u'< Response is nondeterministic due to '
u'invalid validity field: %r' %
(valid_text))
# Parse the business name and address if possible.
try:
name_node = get_first_child_element(
check_vat_response_node,
'ns2:name'
)
result.business_name = get_text(name_node).strip() or None
except Exception:
pass
try:
address_node = get_first_child_element(
check_vat_response_node,
'ns2:address'
)
result.business_address = get_text(address_node).strip() or None
except Exception:
pass
# Parse the country code if possible.
try:
country_code_node = get_first_child_element(
check_vat_response_node,
'ns2:countryCode'
)
result.business_country_code = get_text(country_code_node).strip() or None
except Exception:
pass
return result
|
(self, vat_number, country_code)
|
723,006 |
pyvat
|
check_vat_number
|
Check if a VAT number is valid.
If possible, the VAT number will be checked against available registries.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
guarantee that naively entered VAT numbers contain the correct alpha-2
country code prefix for EU countries just as not all non-EU countries
have a reliable country code prefix. Default ``None`` prompting
detection.
:returns:
a :class:`VatNumberCheckResult` instance containing the result for
the full VAT number check.
|
def check_vat_number(vat_number, country_code=None):
"""Check if a VAT number is valid.
If possible, the VAT number will be checked against available registries.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
guarantee that naively entered VAT numbers contain the correct alpha-2
country code prefix for EU countries just as not all non-EU countries
have a reliable country code prefix. Default ``None`` prompting
detection.
:returns:
a :class:`VatNumberCheckResult` instance containing the result for
the full VAT number check.
"""
# Decompose the VAT number.
vat_number, country_code = decompose_vat_number(vat_number, country_code)
if not vat_number or not country_code:
return VatNumberCheckResult(False, [
'> Unable to decompose VAT number, resulted in %r and %r' %
(vat_number, country_code)
])
# Test the VAT number format.
format_result = is_vat_number_format_valid(vat_number, country_code)
if format_result is not True:
return VatNumberCheckResult(format_result, [
'> VAT number validation failed: %r' % (format_result)
])
# Attempt to check the VAT number against a registry.
if country_code not in VAT_REGISTRIES:
return VatNumberCheckResult()
return VAT_REGISTRIES[country_code].check_vat_number(vat_number,
country_code)
|
(vat_number, country_code=None)
|
723,008 |
pyvat
|
decompose_vat_number
|
Decompose a VAT number and an optional country code.
:param vat_number: VAT number.
:param country_code:
Optional country code. Default ``None`` prompting detection from the
VAT number.
:returns:
a :class:`tuple` containing the VAT number and country code or
``(vat_number, None)`` if decomposition failed.
|
def decompose_vat_number(vat_number, country_code=None):
"""Decompose a VAT number and an optional country code.
:param vat_number: VAT number.
:param country_code:
Optional country code. Default ``None`` prompting detection from the
VAT number.
:returns:
a :class:`tuple` containing the VAT number and country code or
``(vat_number, None)`` if decomposition failed.
"""
# Clean the VAT number.
vat_number = WHITESPACE_EXPRESSION.sub('', vat_number).upper()
# Attempt to determine the country code of the VAT number if possible.
if not country_code:
country_code = vat_number[0:2]
if any(c.isdigit() for c in country_code):
# Country code should not contain digits
return (vat_number, None)
# Non-ISO code used for Greece.
if country_code == 'EL':
country_code = 'GR'
if country_code not in VAT_REGISTRIES:
try:
if not pycountry.countries.get(alpha_2=country_code):
return (vat_number, None)
except KeyError:
# country code not found
return (vat_number, None)
vat_number = vat_number[2:]
elif vat_number[0:2] == country_code:
vat_number = vat_number[2:]
elif country_code == 'GR' and vat_number[0:2] == 'EL':
vat_number = vat_number[2:]
return vat_number, country_code
|
(vat_number, country_code=None)
|
723,010 |
pyvat
|
get_sale_vat_charge
|
Get the VAT charge for performing the sale of an item.
Currently only supports determination of the VAT charge for
telecommunications, broadcasting and electronic services in the EU.
:param date: Sale date.
:type date: datetime.date
:param item_type: Type of the item being sold.
:type item_type: ItemType
:param buyer: Buyer.
:type buyer: Party
:param seller: Seller.
:type seller: Party
:rtype: VatCharge
|
def get_sale_vat_charge(date,
item_type,
buyer,
seller):
"""Get the VAT charge for performing the sale of an item.
Currently only supports determination of the VAT charge for
telecommunications, broadcasting and electronic services in the EU.
:param date: Sale date.
:type date: datetime.date
:param item_type: Type of the item being sold.
:type item_type: ItemType
:param buyer: Buyer.
:type buyer: Party
:param seller: Seller.
:type seller: Party
:rtype: VatCharge
"""
# Only telecommunications, broadcasting and electronic services are
# currently supported.
if not item_type.is_electronic_service and \
not item_type.is_telecommunications_service and \
not item_type.is_broadcasting_service:
raise NotImplementedError(
'VAT charge determination for items that are not '
'telecommunications, broadcasting or electronic services is '
'currently not supported'
)
# Determine the rules for the countries in which the buyer and seller
# reside.
buyer_vat_rules = VAT_RULES.get(buyer.country_code, None)
seller_vat_rules = VAT_RULES.get(seller.country_code, None)
# Test if the country to which the item is being sold enforces specific
# VAT rules for selling to the given country.
if buyer_vat_rules:
try:
return buyer_vat_rules.get_sale_to_country_vat_charge(date,
item_type,
buyer,
seller)
except NotImplementedError:
pass
# Fall back to applying VAT rules for selling from the seller's country.
if seller_vat_rules:
try:
return seller_vat_rules.get_sale_from_country_vat_charge(date,
item_type,
buyer,
seller)
except NotImplementedError:
pass
# Nothing we can do from here.
raise NotImplementedError(
'cannot determine VAT charge for a sale of item %r between %r and %r' %
(item_type, seller, buyer)
)
|
(date, item_type, buyer, seller)
|
723,011 |
pyvat
|
is_vat_number_format_valid
|
Test if the format of a VAT number is valid.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
guarantee that naively entered VAT numbers contain the correct alpha-2
country code prefix for EU countries just as not all non-EU countries
have a reliable country code prefix. Default ``None`` prompting
detection.
:returns:
``True`` if the format of the VAT number can be fully asserted as valid
or ``False`` if not.
|
def is_vat_number_format_valid(vat_number, country_code=None):
"""Test if the format of a VAT number is valid.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
guarantee that naively entered VAT numbers contain the correct alpha-2
country code prefix for EU countries just as not all non-EU countries
have a reliable country code prefix. Default ``None`` prompting
detection.
:returns:
``True`` if the format of the VAT number can be fully asserted as valid
or ``False`` if not.
"""
vat_number, country_code = decompose_vat_number(vat_number, country_code)
if not vat_number or not country_code:
return False
elif not any(c.isdigit() for c in vat_number):
return False
elif country_code not in VAT_NUMBER_EXPRESSIONS:
return False
elif not VAT_NUMBER_EXPRESSIONS[country_code].match(vat_number):
return False
return True
|
(vat_number, country_code=None)
|
723,023 |
varint
|
_byte
| null |
def _byte(b):
return bytes((b, ))
|
(b)
|
723,024 |
varint
|
_read_one
|
Read a byte from the file (as an integer)
raises EOFError if the stream ends while reading bytes.
|
def _read_one(stream):
"""Read a byte from the file (as an integer)
raises EOFError if the stream ends while reading bytes.
"""
c = stream.read(1)
if c == '':
raise EOFError("Unexpected EOF while reading bytes")
return ord(c)
|
(stream)
|
723,025 |
varint
|
decode_bytes
|
Read a varint from from `buf` bytes
|
def decode_bytes(buf):
"""Read a varint from from `buf` bytes"""
return decode_stream(BytesIO(buf))
|
(buf)
|
723,026 |
varint
|
decode_stream
|
Read a varint from `stream`
|
def decode_stream(stream):
"""Read a varint from `stream`"""
shift = 0
result = 0
while True:
i = _read_one(stream)
result |= (i & 0x7f) << shift
shift += 7
if not (i & 0x80):
break
return result
|
(stream)
|
723,027 |
varint
|
encode
|
Pack `number` into varint bytes
|
def encode(number):
"""Pack `number` into varint bytes"""
buf = b''
while True:
towrite = number & 0x7f
number >>= 7
if number:
buf += _byte(towrite | 0x80)
else:
buf += _byte(towrite)
break
return buf
|
(number)
|
723,029 |
isort.settings
|
Config
| null |
class Config(_Config):
def __init__(
self,
settings_file: str = "",
settings_path: str = "",
config: Optional[_Config] = None,
**config_overrides: Any,
):
self._known_patterns: Optional[List[Tuple[Pattern[str], str]]] = None
self._section_comments: Optional[Tuple[str, ...]] = None
self._section_comments_end: Optional[Tuple[str, ...]] = None
self._skips: Optional[FrozenSet[str]] = None
self._skip_globs: Optional[FrozenSet[str]] = None
self._sorting_function: Optional[Callable[..., List[str]]] = None
if config:
config_vars = vars(config).copy()
config_vars.update(config_overrides)
config_vars["py_version"] = config_vars["py_version"].replace("py", "")
config_vars.pop("_known_patterns")
config_vars.pop("_section_comments")
config_vars.pop("_section_comments_end")
config_vars.pop("_skips")
config_vars.pop("_skip_globs")
config_vars.pop("_sorting_function")
super().__init__(**config_vars)
return
# We can't use self.quiet to conditionally show warnings before super.__init__() is called
# at the end of this method. _Config is also frozen so setting self.quiet isn't possible.
# Therefore we extract quiet early here in a variable and use that in warning conditions.
quiet = config_overrides.get("quiet", False)
sources: List[Dict[str, Any]] = [_DEFAULT_SETTINGS]
config_settings: Dict[str, Any]
project_root: str
if settings_file:
config_settings = _get_config_data(
settings_file,
CONFIG_SECTIONS.get(os.path.basename(settings_file), FALLBACK_CONFIG_SECTIONS),
)
project_root = os.path.dirname(settings_file)
if not config_settings and not quiet:
warn(
f"A custom settings file was specified: {settings_file} but no configuration "
"was found inside. This can happen when [settings] is used as the config "
"header instead of [isort]. "
"See: https://pycqa.github.io/isort/docs/configuration/config_files"
"/#custom_config_files for more information."
)
elif settings_path:
if not os.path.exists(settings_path):
raise InvalidSettingsPath(settings_path)
settings_path = os.path.abspath(settings_path)
project_root, config_settings = _find_config(settings_path)
else:
config_settings = {}
project_root = os.getcwd()
profile_name = config_overrides.get("profile", config_settings.get("profile", ""))
profile: Dict[str, Any] = {}
if profile_name:
if profile_name not in profiles:
import pkg_resources
for plugin in pkg_resources.iter_entry_points("isort.profiles"):
profiles.setdefault(plugin.name, plugin.load())
if profile_name not in profiles:
raise ProfileDoesNotExist(profile_name)
profile = profiles[profile_name].copy()
profile["source"] = f"{profile_name} profile"
sources.append(profile)
if config_settings:
sources.append(config_settings)
if config_overrides:
config_overrides["source"] = RUNTIME_SOURCE
sources.append(config_overrides)
combined_config = {**profile, **config_settings, **config_overrides}
if "indent" in combined_config:
indent = str(combined_config["indent"])
if indent.isdigit():
indent = " " * int(indent)
else:
indent = indent.strip("'").strip('"')
if indent.lower() == "tab":
indent = "\t"
combined_config["indent"] = indent
known_other = {}
import_headings = {}
import_footers = {}
for key, value in tuple(combined_config.items()):
# Collect all known sections beyond those that have direct entries
if key.startswith(KNOWN_PREFIX) and key not in (
"known_standard_library",
"known_future_library",
"known_third_party",
"known_first_party",
"known_local_folder",
):
import_heading = key[len(KNOWN_PREFIX) :].lower()
maps_to_section = import_heading.upper()
combined_config.pop(key)
if maps_to_section in KNOWN_SECTION_MAPPING:
section_name = f"known_{KNOWN_SECTION_MAPPING[maps_to_section].lower()}"
if section_name in combined_config and not quiet:
warn(
f"Can't set both {key} and {section_name} in the same config file.\n"
f"Default to {section_name} if unsure."
"\n\n"
"See: https://pycqa.github.io/isort/"
"#custom-sections-and-ordering."
)
else:
combined_config[section_name] = frozenset(value)
else:
known_other[import_heading] = frozenset(value)
if maps_to_section not in combined_config.get("sections", ()) and not quiet:
warn(
f"`{key}` setting is defined, but {maps_to_section} is not"
" included in `sections` config option:"
f" {combined_config.get('sections', SECTION_DEFAULTS)}.\n\n"
"See: https://pycqa.github.io/isort/"
"#custom-sections-and-ordering."
)
if key.startswith(IMPORT_HEADING_PREFIX):
import_headings[key[len(IMPORT_HEADING_PREFIX) :].lower()] = str(value)
if key.startswith(IMPORT_FOOTER_PREFIX):
import_footers[key[len(IMPORT_FOOTER_PREFIX) :].lower()] = str(value)
# Coerce all provided config values into their correct type
default_value = _DEFAULT_SETTINGS.get(key, None)
if default_value is None:
continue
combined_config[key] = type(default_value)(value)
for section in combined_config.get("sections", ()):
if section in SECTION_DEFAULTS:
continue
if not section.lower() in known_other:
config_keys = ", ".join(known_other.keys())
warn(
f"`sections` setting includes {section}, but no known_{section.lower()} "
"is defined. "
f"The following known_SECTION config options are defined: {config_keys}."
)
if "directory" not in combined_config:
combined_config["directory"] = (
os.path.dirname(config_settings["source"])
if config_settings.get("source", None)
else os.getcwd()
)
path_root = Path(combined_config.get("directory", project_root)).resolve()
path_root = path_root if path_root.is_dir() else path_root.parent
if "src_paths" not in combined_config:
combined_config["src_paths"] = (path_root / "src", path_root)
else:
src_paths: List[Path] = []
for src_path in combined_config.get("src_paths", ()):
full_paths = (
path_root.glob(src_path) if "*" in str(src_path) else [path_root / src_path]
)
for path in full_paths:
if path not in src_paths:
src_paths.append(path)
combined_config["src_paths"] = tuple(src_paths)
if "formatter" in combined_config:
import pkg_resources
for plugin in pkg_resources.iter_entry_points("isort.formatters"):
if plugin.name == combined_config["formatter"]:
combined_config["formatting_function"] = plugin.load()
break
else:
raise FormattingPluginDoesNotExist(combined_config["formatter"])
# Remove any config values that are used for creating config object but
# aren't defined in dataclass
combined_config.pop("source", None)
combined_config.pop("sources", None)
combined_config.pop("runtime_src_paths", None)
deprecated_options_used = [
option for option in combined_config if option in DEPRECATED_SETTINGS
]
if deprecated_options_used:
for deprecated_option in deprecated_options_used:
combined_config.pop(deprecated_option)
if not quiet:
warn(
"W0503: Deprecated config options were used: "
f"{', '.join(deprecated_options_used)}."
"Please see the 5.0.0 upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html"
)
if known_other:
combined_config["known_other"] = known_other
if import_headings:
for import_heading_key in import_headings:
combined_config.pop(f"{IMPORT_HEADING_PREFIX}{import_heading_key}")
combined_config["import_headings"] = import_headings
if import_footers:
for import_footer_key in import_footers:
combined_config.pop(f"{IMPORT_FOOTER_PREFIX}{import_footer_key}")
combined_config["import_footers"] = import_footers
unsupported_config_errors = {}
for option in set(combined_config.keys()).difference(
getattr(_Config, "__dataclass_fields__", {}).keys()
):
for source in reversed(sources):
if option in source:
unsupported_config_errors[option] = {
"value": source[option],
"source": source["source"],
}
if unsupported_config_errors:
raise UnsupportedSettings(unsupported_config_errors)
super().__init__(sources=tuple(sources), **combined_config)
def is_supported_filetype(self, file_name: str) -> bool:
_root, ext = os.path.splitext(file_name)
ext = ext.lstrip(".")
if ext in self.supported_extensions:
return True
if ext in self.blocked_extensions:
return False
# Skip editor backup files.
if file_name.endswith("~"):
return False
try:
if stat.S_ISFIFO(os.stat(file_name).st_mode):
return False
except OSError:
pass
try:
with open(file_name, "rb") as fp:
line = fp.readline(100)
except OSError:
return False
else:
return bool(_SHEBANG_RE.match(line))
def _check_folder_git_ls_files(self, folder: str) -> Optional[Path]:
env = {**os.environ, "LANG": "C.UTF-8"}
try:
topfolder_result = subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", folder, "rev-parse", "--show-toplevel"], encoding="utf-8", env=env
)
except subprocess.CalledProcessError:
return None
git_folder = Path(topfolder_result.rstrip()).resolve()
# files committed to git
tracked_files = (
subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", str(git_folder), "ls-files", "-z"],
encoding="utf-8",
env=env,
)
.rstrip("\0")
.split("\0")
)
# files that haven't been committed yet, but aren't ignored
tracked_files_others = (
subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", str(git_folder), "ls-files", "-z", "--others", "--exclude-standard"],
encoding="utf-8",
env=env,
)
.rstrip("\0")
.split("\0")
)
self.git_ls_files[git_folder] = {
str(git_folder / Path(f)) for f in tracked_files + tracked_files_others
}
return git_folder
def is_skipped(self, file_path: Path) -> bool:
"""Returns True if the file and/or folder should be skipped based on current settings."""
if self.directory and Path(self.directory) in file_path.resolve().parents:
file_name = os.path.relpath(file_path.resolve(), self.directory)
else:
file_name = str(file_path)
os_path = str(file_path)
normalized_path = os_path.replace("\\", "/")
if normalized_path[1:2] == ":":
normalized_path = normalized_path[2:]
for skip_path in self.skips:
if posixpath.abspath(normalized_path) == posixpath.abspath(
skip_path.replace("\\", "/")
):
return True
position = os.path.split(file_name)
while position[1]:
if position[1] in self.skips:
return True
position = os.path.split(position[0])
for sglob in self.skip_globs:
if fnmatch.fnmatch(file_name, sglob) or fnmatch.fnmatch("/" + file_name, sglob):
return True
if not (os.path.isfile(os_path) or os.path.isdir(os_path) or os.path.islink(os_path)):
return True
if self.skip_gitignore:
if file_path.name == ".git": # pragma: no cover
return True
git_folder = None
file_paths = [file_path, file_path.resolve()]
for folder in self.git_ls_files:
if any(folder in path.parents for path in file_paths):
git_folder = folder
break
else:
git_folder = self._check_folder_git_ls_files(str(file_path.parent))
# git_ls_files are good files you should parse. If you're not in the allow list, skip.
if (
git_folder
and not file_path.is_dir()
and str(file_path.resolve()) not in self.git_ls_files[git_folder]
):
return True
return False
@property
def known_patterns(self) -> List[Tuple[Pattern[str], str]]:
if self._known_patterns is not None:
return self._known_patterns
self._known_patterns = []
pattern_sections = [STDLIB] + [section for section in self.sections if section != STDLIB]
for placement in reversed(pattern_sections):
known_placement = KNOWN_SECTION_MAPPING.get(placement, placement).lower()
config_key = f"{KNOWN_PREFIX}{known_placement}"
known_modules = getattr(self, config_key, self.known_other.get(known_placement, ()))
extra_modules = getattr(self, f"extra_{known_placement}", ())
all_modules = set(extra_modules).union(known_modules)
known_patterns = [
pattern
for known_pattern in all_modules
for pattern in self._parse_known_pattern(known_pattern)
]
for known_pattern in known_patterns:
regexp = "^" + known_pattern.replace("*", ".*").replace("?", ".?") + "$"
self._known_patterns.append((re.compile(regexp), placement))
return self._known_patterns
@property
def section_comments(self) -> Tuple[str, ...]:
if self._section_comments is not None:
return self._section_comments
self._section_comments = tuple(f"# {heading}" for heading in self.import_headings.values())
return self._section_comments
@property
def section_comments_end(self) -> Tuple[str, ...]:
if self._section_comments_end is not None:
return self._section_comments_end
self._section_comments_end = tuple(f"# {footer}" for footer in self.import_footers.values())
return self._section_comments_end
@property
def skips(self) -> FrozenSet[str]:
if self._skips is not None:
return self._skips
self._skips = self.skip.union(self.extend_skip)
return self._skips
@property
def skip_globs(self) -> FrozenSet[str]:
if self._skip_globs is not None:
return self._skip_globs
self._skip_globs = self.skip_glob.union(self.extend_skip_glob)
return self._skip_globs
@property
def sorting_function(self) -> Callable[..., List[str]]:
if self._sorting_function is not None:
return self._sorting_function
if self.sort_order == "natural":
self._sorting_function = sorting.naturally
elif self.sort_order == "native":
self._sorting_function = sorted
else:
available_sort_orders = ["natural", "native"]
import pkg_resources
for sort_plugin in pkg_resources.iter_entry_points("isort.sort_function"):
available_sort_orders.append(sort_plugin.name)
if sort_plugin.name == self.sort_order:
self._sorting_function = sort_plugin.load()
break
else:
raise SortingFunctionDoesNotExist(self.sort_order, available_sort_orders)
return self._sorting_function
def _parse_known_pattern(self, pattern: str) -> List[str]:
"""Expand pattern if identified as a directory and return found sub packages"""
if pattern.endswith(os.path.sep):
patterns = [
filename
for filename in os.listdir(os.path.join(self.directory, pattern))
if os.path.isdir(os.path.join(self.directory, pattern, filename))
]
else:
patterns = [pattern]
return patterns
|
(settings_file: str = '', settings_path: str = '', config: Optional[isort.settings._Config] = None, **config_overrides: Any)
|
723,030 |
isort.settings
|
__delattr__
| null |
"""isort/settings.py.
Defines how the default settings for isort should be loaded
"""
import configparser
import fnmatch
import os
import posixpath
import re
import stat
import subprocess # nosec: Needed for gitignore support.
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
FrozenSet,
Iterable,
List,
Optional,
Pattern,
Set,
Tuple,
Type,
Union,
)
from warnings import warn
from . import sorting, stdlibs
from .exceptions import (
FormattingPluginDoesNotExist,
InvalidSettingsPath,
ProfileDoesNotExist,
SortingFunctionDoesNotExist,
UnsupportedSettings,
)
from .profiles import profiles as profiles
from .sections import DEFAULT as SECTION_DEFAULTS
from .sections import FIRSTPARTY, FUTURE, LOCALFOLDER, STDLIB, THIRDPARTY
from .utils import Trie
from .wrap_modes import WrapModes
from .wrap_modes import from_string as wrap_mode_from_string
if TYPE_CHECKING:
tomllib: Any
else:
if sys.version_info >= (3, 11):
import tomllib
else:
from ._vendored import tomli as tomllib
_SHEBANG_RE = re.compile(rb"^#!.*\bpython[23w]?\b")
CYTHON_EXTENSIONS = frozenset({"pyx", "pxd"})
SUPPORTED_EXTENSIONS = frozenset({"py", "pyi", *CYTHON_EXTENSIONS})
BLOCKED_EXTENSIONS = frozenset({"pex"})
FILE_SKIP_COMMENTS: Tuple[str, ...] = (
"isort:" + "skip_file",
"isort: " + "skip_file",
) # Concatenated to avoid this file being skipped
MAX_CONFIG_SEARCH_DEPTH: int = 25 # The number of parent directories to for a config file within
STOP_CONFIG_SEARCH_ON_DIRS: Tuple[str, ...] = (".git", ".hg")
VALID_PY_TARGETS: Tuple[str, ...] = tuple(
target.replace("py", "") for target in dir(stdlibs) if not target.startswith("_")
)
CONFIG_SOURCES: Tuple[str, ...] = (
".isort.cfg",
"pyproject.toml",
"setup.cfg",
"tox.ini",
".editorconfig",
)
DEFAULT_SKIP: FrozenSet[str] = frozenset(
{
".venv",
"venv",
".tox",
".eggs",
".git",
".hg",
".mypy_cache",
".nox",
".svn",
".bzr",
"_build",
"buck-out",
"build",
"dist",
".pants.d",
".direnv",
"node_modules",
"__pypackages__",
".pytype",
}
)
CONFIG_SECTIONS: Dict[str, Tuple[str, ...]] = {
".isort.cfg": ("settings", "isort"),
"pyproject.toml": ("tool.isort",),
"setup.cfg": ("isort", "tool:isort"),
"tox.ini": ("isort", "tool:isort"),
".editorconfig": ("*", "*.py", "**.py", "*.{py}"),
}
FALLBACK_CONFIG_SECTIONS: Tuple[str, ...] = ("isort", "tool:isort", "tool.isort")
IMPORT_HEADING_PREFIX = "import_heading_"
IMPORT_FOOTER_PREFIX = "import_footer_"
KNOWN_PREFIX = "known_"
KNOWN_SECTION_MAPPING: Dict[str, str] = {
STDLIB: "STANDARD_LIBRARY",
FUTURE: "FUTURE_LIBRARY",
FIRSTPARTY: "FIRST_PARTY",
THIRDPARTY: "THIRD_PARTY",
LOCALFOLDER: "LOCAL_FOLDER",
}
RUNTIME_SOURCE = "runtime"
DEPRECATED_SETTINGS = ("not_skip", "keep_direct_and_as_imports")
_STR_BOOLEAN_MAPPING = {
"y": True,
"yes": True,
"t": True,
"on": True,
"1": True,
"true": True,
"n": False,
"no": False,
"f": False,
"off": False,
"0": False,
"false": False,
}
@dataclass(frozen=True)
class _Config:
"""Defines the data schema and defaults used for isort configuration.
NOTE: known lists, such as known_standard_library, are intentionally not complete as they are
dynamically determined later on.
"""
py_version: str = "3"
force_to_top: FrozenSet[str] = frozenset()
skip: FrozenSet[str] = DEFAULT_SKIP
extend_skip: FrozenSet[str] = frozenset()
skip_glob: FrozenSet[str] = frozenset()
extend_skip_glob: FrozenSet[str] = frozenset()
skip_gitignore: bool = False
line_length: int = 79
wrap_length: int = 0
line_ending: str = ""
sections: Tuple[str, ...] = SECTION_DEFAULTS
no_sections: bool = False
known_future_library: FrozenSet[str] = frozenset(("__future__",))
known_third_party: FrozenSet[str] = frozenset()
known_first_party: FrozenSet[str] = frozenset()
known_local_folder: FrozenSet[str] = frozenset()
known_standard_library: FrozenSet[str] = frozenset()
extra_standard_library: FrozenSet[str] = frozenset()
known_other: Dict[str, FrozenSet[str]] = field(default_factory=dict)
multi_line_output: WrapModes = WrapModes.GRID # type: ignore
forced_separate: Tuple[str, ...] = ()
indent: str = " " * 4
comment_prefix: str = " #"
length_sort: bool = False
length_sort_straight: bool = False
length_sort_sections: FrozenSet[str] = frozenset()
add_imports: FrozenSet[str] = frozenset()
remove_imports: FrozenSet[str] = frozenset()
append_only: bool = False
reverse_relative: bool = False
force_single_line: bool = False
single_line_exclusions: Tuple[str, ...] = ()
default_section: str = THIRDPARTY
import_headings: Dict[str, str] = field(default_factory=dict)
import_footers: Dict[str, str] = field(default_factory=dict)
balanced_wrapping: bool = False
use_parentheses: bool = False
order_by_type: bool = True
atomic: bool = False
lines_before_imports: int = -1
lines_after_imports: int = -1
lines_between_sections: int = 1
lines_between_types: int = 0
combine_as_imports: bool = False
combine_star: bool = False
include_trailing_comma: bool = False
from_first: bool = False
verbose: bool = False
quiet: bool = False
force_adds: bool = False
force_alphabetical_sort_within_sections: bool = False
force_alphabetical_sort: bool = False
force_grid_wrap: int = 0
force_sort_within_sections: bool = False
lexicographical: bool = False
group_by_package: bool = False
ignore_whitespace: bool = False
no_lines_before: FrozenSet[str] = frozenset()
no_inline_sort: bool = False
ignore_comments: bool = False
case_sensitive: bool = False
sources: Tuple[Dict[str, Any], ...] = ()
virtual_env: str = ""
conda_env: str = ""
ensure_newline_before_comments: bool = False
directory: str = ""
profile: str = ""
honor_noqa: bool = False
src_paths: Tuple[Path, ...] = ()
old_finders: bool = False
remove_redundant_aliases: bool = False
float_to_top: bool = False
filter_files: bool = False
formatter: str = ""
formatting_function: Optional[Callable[[str, str, object], str]] = None
color_output: bool = False
treat_comments_as_code: FrozenSet[str] = frozenset()
treat_all_comments_as_code: bool = False
supported_extensions: FrozenSet[str] = SUPPORTED_EXTENSIONS
blocked_extensions: FrozenSet[str] = BLOCKED_EXTENSIONS
constants: FrozenSet[str] = frozenset()
classes: FrozenSet[str] = frozenset()
variables: FrozenSet[str] = frozenset()
dedup_headings: bool = False
only_sections: bool = False
only_modified: bool = False
combine_straight_imports: bool = False
auto_identify_namespace_packages: bool = True
namespace_packages: FrozenSet[str] = frozenset()
follow_links: bool = True
indented_import_headings: bool = True
honor_case_in_force_sorted_sections: bool = False
sort_relative_in_force_sorted_sections: bool = False
overwrite_in_place: bool = False
reverse_sort: bool = False
star_first: bool = False
import_dependencies = Dict[str, str]
git_ls_files: Dict[Path, Set[str]] = field(default_factory=dict)
format_error: str = "{error}: {message}"
format_success: str = "{success}: {message}"
sort_order: str = "natural"
sort_reexports: bool = False
split_on_trailing_comma: bool = False
def __post_init__(self) -> None:
py_version = self.py_version
if py_version == "auto": # pragma: no cover
if sys.version_info.major == 2 and sys.version_info.minor <= 6:
py_version = "2"
elif sys.version_info.major == 3 and (
sys.version_info.minor <= 5 or sys.version_info.minor >= 12
):
py_version = "3"
else:
py_version = f"{sys.version_info.major}{sys.version_info.minor}"
if py_version not in VALID_PY_TARGETS:
raise ValueError(
f"The python version {py_version} is not supported. "
"You can set a python version with the -py or --python-version flag. "
f"The following versions are supported: {VALID_PY_TARGETS}"
)
if py_version != "all":
object.__setattr__(self, "py_version", f"py{py_version}")
if not self.known_standard_library:
object.__setattr__(
self, "known_standard_library", frozenset(getattr(stdlibs, self.py_version).stdlib)
)
if self.multi_line_output == WrapModes.VERTICAL_GRID_GROUPED_NO_COMMA: # type: ignore
vertical_grid_grouped = WrapModes.VERTICAL_GRID_GROUPED # type: ignore
object.__setattr__(self, "multi_line_output", vertical_grid_grouped)
if self.force_alphabetical_sort:
object.__setattr__(self, "force_alphabetical_sort_within_sections", True)
object.__setattr__(self, "no_sections", True)
object.__setattr__(self, "lines_between_types", 1)
object.__setattr__(self, "from_first", True)
if self.wrap_length > self.line_length:
raise ValueError(
"wrap_length must be set lower than or equal to line_length: "
f"{self.wrap_length} > {self.line_length}."
)
def __hash__(self) -> int:
return id(self)
|
(self, name)
|
723,033 |
isort.settings
|
__init__
| null |
def __init__(
self,
settings_file: str = "",
settings_path: str = "",
config: Optional[_Config] = None,
**config_overrides: Any,
):
self._known_patterns: Optional[List[Tuple[Pattern[str], str]]] = None
self._section_comments: Optional[Tuple[str, ...]] = None
self._section_comments_end: Optional[Tuple[str, ...]] = None
self._skips: Optional[FrozenSet[str]] = None
self._skip_globs: Optional[FrozenSet[str]] = None
self._sorting_function: Optional[Callable[..., List[str]]] = None
if config:
config_vars = vars(config).copy()
config_vars.update(config_overrides)
config_vars["py_version"] = config_vars["py_version"].replace("py", "")
config_vars.pop("_known_patterns")
config_vars.pop("_section_comments")
config_vars.pop("_section_comments_end")
config_vars.pop("_skips")
config_vars.pop("_skip_globs")
config_vars.pop("_sorting_function")
super().__init__(**config_vars)
return
# We can't use self.quiet to conditionally show warnings before super.__init__() is called
# at the end of this method. _Config is also frozen so setting self.quiet isn't possible.
# Therefore we extract quiet early here in a variable and use that in warning conditions.
quiet = config_overrides.get("quiet", False)
sources: List[Dict[str, Any]] = [_DEFAULT_SETTINGS]
config_settings: Dict[str, Any]
project_root: str
if settings_file:
config_settings = _get_config_data(
settings_file,
CONFIG_SECTIONS.get(os.path.basename(settings_file), FALLBACK_CONFIG_SECTIONS),
)
project_root = os.path.dirname(settings_file)
if not config_settings and not quiet:
warn(
f"A custom settings file was specified: {settings_file} but no configuration "
"was found inside. This can happen when [settings] is used as the config "
"header instead of [isort]. "
"See: https://pycqa.github.io/isort/docs/configuration/config_files"
"/#custom_config_files for more information."
)
elif settings_path:
if not os.path.exists(settings_path):
raise InvalidSettingsPath(settings_path)
settings_path = os.path.abspath(settings_path)
project_root, config_settings = _find_config(settings_path)
else:
config_settings = {}
project_root = os.getcwd()
profile_name = config_overrides.get("profile", config_settings.get("profile", ""))
profile: Dict[str, Any] = {}
if profile_name:
if profile_name not in profiles:
import pkg_resources
for plugin in pkg_resources.iter_entry_points("isort.profiles"):
profiles.setdefault(plugin.name, plugin.load())
if profile_name not in profiles:
raise ProfileDoesNotExist(profile_name)
profile = profiles[profile_name].copy()
profile["source"] = f"{profile_name} profile"
sources.append(profile)
if config_settings:
sources.append(config_settings)
if config_overrides:
config_overrides["source"] = RUNTIME_SOURCE
sources.append(config_overrides)
combined_config = {**profile, **config_settings, **config_overrides}
if "indent" in combined_config:
indent = str(combined_config["indent"])
if indent.isdigit():
indent = " " * int(indent)
else:
indent = indent.strip("'").strip('"')
if indent.lower() == "tab":
indent = "\t"
combined_config["indent"] = indent
known_other = {}
import_headings = {}
import_footers = {}
for key, value in tuple(combined_config.items()):
# Collect all known sections beyond those that have direct entries
if key.startswith(KNOWN_PREFIX) and key not in (
"known_standard_library",
"known_future_library",
"known_third_party",
"known_first_party",
"known_local_folder",
):
import_heading = key[len(KNOWN_PREFIX) :].lower()
maps_to_section = import_heading.upper()
combined_config.pop(key)
if maps_to_section in KNOWN_SECTION_MAPPING:
section_name = f"known_{KNOWN_SECTION_MAPPING[maps_to_section].lower()}"
if section_name in combined_config and not quiet:
warn(
f"Can't set both {key} and {section_name} in the same config file.\n"
f"Default to {section_name} if unsure."
"\n\n"
"See: https://pycqa.github.io/isort/"
"#custom-sections-and-ordering."
)
else:
combined_config[section_name] = frozenset(value)
else:
known_other[import_heading] = frozenset(value)
if maps_to_section not in combined_config.get("sections", ()) and not quiet:
warn(
f"`{key}` setting is defined, but {maps_to_section} is not"
" included in `sections` config option:"
f" {combined_config.get('sections', SECTION_DEFAULTS)}.\n\n"
"See: https://pycqa.github.io/isort/"
"#custom-sections-and-ordering."
)
if key.startswith(IMPORT_HEADING_PREFIX):
import_headings[key[len(IMPORT_HEADING_PREFIX) :].lower()] = str(value)
if key.startswith(IMPORT_FOOTER_PREFIX):
import_footers[key[len(IMPORT_FOOTER_PREFIX) :].lower()] = str(value)
# Coerce all provided config values into their correct type
default_value = _DEFAULT_SETTINGS.get(key, None)
if default_value is None:
continue
combined_config[key] = type(default_value)(value)
for section in combined_config.get("sections", ()):
if section in SECTION_DEFAULTS:
continue
if not section.lower() in known_other:
config_keys = ", ".join(known_other.keys())
warn(
f"`sections` setting includes {section}, but no known_{section.lower()} "
"is defined. "
f"The following known_SECTION config options are defined: {config_keys}."
)
if "directory" not in combined_config:
combined_config["directory"] = (
os.path.dirname(config_settings["source"])
if config_settings.get("source", None)
else os.getcwd()
)
path_root = Path(combined_config.get("directory", project_root)).resolve()
path_root = path_root if path_root.is_dir() else path_root.parent
if "src_paths" not in combined_config:
combined_config["src_paths"] = (path_root / "src", path_root)
else:
src_paths: List[Path] = []
for src_path in combined_config.get("src_paths", ()):
full_paths = (
path_root.glob(src_path) if "*" in str(src_path) else [path_root / src_path]
)
for path in full_paths:
if path not in src_paths:
src_paths.append(path)
combined_config["src_paths"] = tuple(src_paths)
if "formatter" in combined_config:
import pkg_resources
for plugin in pkg_resources.iter_entry_points("isort.formatters"):
if plugin.name == combined_config["formatter"]:
combined_config["formatting_function"] = plugin.load()
break
else:
raise FormattingPluginDoesNotExist(combined_config["formatter"])
# Remove any config values that are used for creating config object but
# aren't defined in dataclass
combined_config.pop("source", None)
combined_config.pop("sources", None)
combined_config.pop("runtime_src_paths", None)
deprecated_options_used = [
option for option in combined_config if option in DEPRECATED_SETTINGS
]
if deprecated_options_used:
for deprecated_option in deprecated_options_used:
combined_config.pop(deprecated_option)
if not quiet:
warn(
"W0503: Deprecated config options were used: "
f"{', '.join(deprecated_options_used)}."
"Please see the 5.0.0 upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0.html"
)
if known_other:
combined_config["known_other"] = known_other
if import_headings:
for import_heading_key in import_headings:
combined_config.pop(f"{IMPORT_HEADING_PREFIX}{import_heading_key}")
combined_config["import_headings"] = import_headings
if import_footers:
for import_footer_key in import_footers:
combined_config.pop(f"{IMPORT_FOOTER_PREFIX}{import_footer_key}")
combined_config["import_footers"] = import_footers
unsupported_config_errors = {}
for option in set(combined_config.keys()).difference(
getattr(_Config, "__dataclass_fields__", {}).keys()
):
for source in reversed(sources):
if option in source:
unsupported_config_errors[option] = {
"value": source[option],
"source": source["source"],
}
if unsupported_config_errors:
raise UnsupportedSettings(unsupported_config_errors)
super().__init__(sources=tuple(sources), **combined_config)
|
(self, settings_file: str = '', settings_path: str = '', config: Optional[isort.settings._Config] = None, **config_overrides: Any)
|
723,034 |
isort.settings
|
__post_init__
| null |
def __post_init__(self) -> None:
py_version = self.py_version
if py_version == "auto": # pragma: no cover
if sys.version_info.major == 2 and sys.version_info.minor <= 6:
py_version = "2"
elif sys.version_info.major == 3 and (
sys.version_info.minor <= 5 or sys.version_info.minor >= 12
):
py_version = "3"
else:
py_version = f"{sys.version_info.major}{sys.version_info.minor}"
if py_version not in VALID_PY_TARGETS:
raise ValueError(
f"The python version {py_version} is not supported. "
"You can set a python version with the -py or --python-version flag. "
f"The following versions are supported: {VALID_PY_TARGETS}"
)
if py_version != "all":
object.__setattr__(self, "py_version", f"py{py_version}")
if not self.known_standard_library:
object.__setattr__(
self, "known_standard_library", frozenset(getattr(stdlibs, self.py_version).stdlib)
)
if self.multi_line_output == WrapModes.VERTICAL_GRID_GROUPED_NO_COMMA: # type: ignore
vertical_grid_grouped = WrapModes.VERTICAL_GRID_GROUPED # type: ignore
object.__setattr__(self, "multi_line_output", vertical_grid_grouped)
if self.force_alphabetical_sort:
object.__setattr__(self, "force_alphabetical_sort_within_sections", True)
object.__setattr__(self, "no_sections", True)
object.__setattr__(self, "lines_between_types", 1)
object.__setattr__(self, "from_first", True)
if self.wrap_length > self.line_length:
raise ValueError(
"wrap_length must be set lower than or equal to line_length: "
f"{self.wrap_length} > {self.line_length}."
)
|
(self) -> NoneType
|
723,035 |
isort.settings
|
__repr__
| null |
@dataclass(frozen=True)
class _Config:
"""Defines the data schema and defaults used for isort configuration.
NOTE: known lists, such as known_standard_library, are intentionally not complete as they are
dynamically determined later on.
"""
py_version: str = "3"
force_to_top: FrozenSet[str] = frozenset()
skip: FrozenSet[str] = DEFAULT_SKIP
extend_skip: FrozenSet[str] = frozenset()
skip_glob: FrozenSet[str] = frozenset()
extend_skip_glob: FrozenSet[str] = frozenset()
skip_gitignore: bool = False
line_length: int = 79
wrap_length: int = 0
line_ending: str = ""
sections: Tuple[str, ...] = SECTION_DEFAULTS
no_sections: bool = False
known_future_library: FrozenSet[str] = frozenset(("__future__",))
known_third_party: FrozenSet[str] = frozenset()
known_first_party: FrozenSet[str] = frozenset()
known_local_folder: FrozenSet[str] = frozenset()
known_standard_library: FrozenSet[str] = frozenset()
extra_standard_library: FrozenSet[str] = frozenset()
known_other: Dict[str, FrozenSet[str]] = field(default_factory=dict)
multi_line_output: WrapModes = WrapModes.GRID # type: ignore
forced_separate: Tuple[str, ...] = ()
indent: str = " " * 4
comment_prefix: str = " #"
length_sort: bool = False
length_sort_straight: bool = False
length_sort_sections: FrozenSet[str] = frozenset()
add_imports: FrozenSet[str] = frozenset()
remove_imports: FrozenSet[str] = frozenset()
append_only: bool = False
reverse_relative: bool = False
force_single_line: bool = False
single_line_exclusions: Tuple[str, ...] = ()
default_section: str = THIRDPARTY
import_headings: Dict[str, str] = field(default_factory=dict)
import_footers: Dict[str, str] = field(default_factory=dict)
balanced_wrapping: bool = False
use_parentheses: bool = False
order_by_type: bool = True
atomic: bool = False
lines_before_imports: int = -1
lines_after_imports: int = -1
lines_between_sections: int = 1
lines_between_types: int = 0
combine_as_imports: bool = False
combine_star: bool = False
include_trailing_comma: bool = False
from_first: bool = False
verbose: bool = False
quiet: bool = False
force_adds: bool = False
force_alphabetical_sort_within_sections: bool = False
force_alphabetical_sort: bool = False
force_grid_wrap: int = 0
force_sort_within_sections: bool = False
lexicographical: bool = False
group_by_package: bool = False
ignore_whitespace: bool = False
no_lines_before: FrozenSet[str] = frozenset()
no_inline_sort: bool = False
ignore_comments: bool = False
case_sensitive: bool = False
sources: Tuple[Dict[str, Any], ...] = ()
virtual_env: str = ""
conda_env: str = ""
ensure_newline_before_comments: bool = False
directory: str = ""
profile: str = ""
honor_noqa: bool = False
src_paths: Tuple[Path, ...] = ()
old_finders: bool = False
remove_redundant_aliases: bool = False
float_to_top: bool = False
filter_files: bool = False
formatter: str = ""
formatting_function: Optional[Callable[[str, str, object], str]] = None
color_output: bool = False
treat_comments_as_code: FrozenSet[str] = frozenset()
treat_all_comments_as_code: bool = False
supported_extensions: FrozenSet[str] = SUPPORTED_EXTENSIONS
blocked_extensions: FrozenSet[str] = BLOCKED_EXTENSIONS
constants: FrozenSet[str] = frozenset()
classes: FrozenSet[str] = frozenset()
variables: FrozenSet[str] = frozenset()
dedup_headings: bool = False
only_sections: bool = False
only_modified: bool = False
combine_straight_imports: bool = False
auto_identify_namespace_packages: bool = True
namespace_packages: FrozenSet[str] = frozenset()
follow_links: bool = True
indented_import_headings: bool = True
honor_case_in_force_sorted_sections: bool = False
sort_relative_in_force_sorted_sections: bool = False
overwrite_in_place: bool = False
reverse_sort: bool = False
star_first: bool = False
import_dependencies = Dict[str, str]
git_ls_files: Dict[Path, Set[str]] = field(default_factory=dict)
format_error: str = "{error}: {message}"
format_success: str = "{success}: {message}"
sort_order: str = "natural"
sort_reexports: bool = False
split_on_trailing_comma: bool = False
def __post_init__(self) -> None:
py_version = self.py_version
if py_version == "auto": # pragma: no cover
if sys.version_info.major == 2 and sys.version_info.minor <= 6:
py_version = "2"
elif sys.version_info.major == 3 and (
sys.version_info.minor <= 5 or sys.version_info.minor >= 12
):
py_version = "3"
else:
py_version = f"{sys.version_info.major}{sys.version_info.minor}"
if py_version not in VALID_PY_TARGETS:
raise ValueError(
f"The python version {py_version} is not supported. "
"You can set a python version with the -py or --python-version flag. "
f"The following versions are supported: {VALID_PY_TARGETS}"
)
if py_version != "all":
object.__setattr__(self, "py_version", f"py{py_version}")
if not self.known_standard_library:
object.__setattr__(
self, "known_standard_library", frozenset(getattr(stdlibs, self.py_version).stdlib)
)
if self.multi_line_output == WrapModes.VERTICAL_GRID_GROUPED_NO_COMMA: # type: ignore
vertical_grid_grouped = WrapModes.VERTICAL_GRID_GROUPED # type: ignore
object.__setattr__(self, "multi_line_output", vertical_grid_grouped)
if self.force_alphabetical_sort:
object.__setattr__(self, "force_alphabetical_sort_within_sections", True)
object.__setattr__(self, "no_sections", True)
object.__setattr__(self, "lines_between_types", 1)
object.__setattr__(self, "from_first", True)
if self.wrap_length > self.line_length:
raise ValueError(
"wrap_length must be set lower than or equal to line_length: "
f"{self.wrap_length} > {self.line_length}."
)
def __hash__(self) -> int:
return id(self)
|
(self)
|
723,037 |
isort.settings
|
_check_folder_git_ls_files
| null |
def _check_folder_git_ls_files(self, folder: str) -> Optional[Path]:
env = {**os.environ, "LANG": "C.UTF-8"}
try:
topfolder_result = subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", folder, "rev-parse", "--show-toplevel"], encoding="utf-8", env=env
)
except subprocess.CalledProcessError:
return None
git_folder = Path(topfolder_result.rstrip()).resolve()
# files committed to git
tracked_files = (
subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", str(git_folder), "ls-files", "-z"],
encoding="utf-8",
env=env,
)
.rstrip("\0")
.split("\0")
)
# files that haven't been committed yet, but aren't ignored
tracked_files_others = (
subprocess.check_output( # nosec # skipcq: PYL-W1510
["git", "-C", str(git_folder), "ls-files", "-z", "--others", "--exclude-standard"],
encoding="utf-8",
env=env,
)
.rstrip("\0")
.split("\0")
)
self.git_ls_files[git_folder] = {
str(git_folder / Path(f)) for f in tracked_files + tracked_files_others
}
return git_folder
|
(self, folder: str) -> Optional[pathlib.Path]
|
723,038 |
isort.settings
|
_parse_known_pattern
|
Expand pattern if identified as a directory and return found sub packages
|
def _parse_known_pattern(self, pattern: str) -> List[str]:
"""Expand pattern if identified as a directory and return found sub packages"""
if pattern.endswith(os.path.sep):
patterns = [
filename
for filename in os.listdir(os.path.join(self.directory, pattern))
if os.path.isdir(os.path.join(self.directory, pattern, filename))
]
else:
patterns = [pattern]
return patterns
|
(self, pattern: str) -> List[str]
|
723,039 |
isort.settings
|
is_skipped
|
Returns True if the file and/or folder should be skipped based on current settings.
|
def is_skipped(self, file_path: Path) -> bool:
"""Returns True if the file and/or folder should be skipped based on current settings."""
if self.directory and Path(self.directory) in file_path.resolve().parents:
file_name = os.path.relpath(file_path.resolve(), self.directory)
else:
file_name = str(file_path)
os_path = str(file_path)
normalized_path = os_path.replace("\\", "/")
if normalized_path[1:2] == ":":
normalized_path = normalized_path[2:]
for skip_path in self.skips:
if posixpath.abspath(normalized_path) == posixpath.abspath(
skip_path.replace("\\", "/")
):
return True
position = os.path.split(file_name)
while position[1]:
if position[1] in self.skips:
return True
position = os.path.split(position[0])
for sglob in self.skip_globs:
if fnmatch.fnmatch(file_name, sglob) or fnmatch.fnmatch("/" + file_name, sglob):
return True
if not (os.path.isfile(os_path) or os.path.isdir(os_path) or os.path.islink(os_path)):
return True
if self.skip_gitignore:
if file_path.name == ".git": # pragma: no cover
return True
git_folder = None
file_paths = [file_path, file_path.resolve()]
for folder in self.git_ls_files:
if any(folder in path.parents for path in file_paths):
git_folder = folder
break
else:
git_folder = self._check_folder_git_ls_files(str(file_path.parent))
# git_ls_files are good files you should parse. If you're not in the allow list, skip.
if (
git_folder
and not file_path.is_dir()
and str(file_path.resolve()) not in self.git_ls_files[git_folder]
):
return True
return False
|
(self, file_path: pathlib.Path) -> bool
|
723,040 |
isort.settings
|
is_supported_filetype
| null |
def is_supported_filetype(self, file_name: str) -> bool:
_root, ext = os.path.splitext(file_name)
ext = ext.lstrip(".")
if ext in self.supported_extensions:
return True
if ext in self.blocked_extensions:
return False
# Skip editor backup files.
if file_name.endswith("~"):
return False
try:
if stat.S_ISFIFO(os.stat(file_name).st_mode):
return False
except OSError:
pass
try:
with open(file_name, "rb") as fp:
line = fp.readline(100)
except OSError:
return False
else:
return bool(_SHEBANG_RE.match(line))
|
(self, file_name: str) -> bool
|
723,041 |
isort.api
|
ImportKey
|
Defines how to key an individual import, generally for deduping.
Import keys are defined from less to more specific:
from x.y import z as a
______| | | |
| | | |
PACKAGE | | |
________| | |
| | |
MODULE | |
_________________| |
| |
ATTRIBUTE |
______________________|
|
ALIAS
|
class ImportKey(Enum):
"""Defines how to key an individual import, generally for deduping.
Import keys are defined from less to more specific:
from x.y import z as a
______| | | |
| | | |
PACKAGE | | |
________| | |
| | |
MODULE | |
_________________| |
| |
ATTRIBUTE |
______________________|
|
ALIAS
"""
PACKAGE = 1
MODULE = 2
ATTRIBUTE = 3
ALIAS = 4
|
(value, names=None, *, module=None, qualname=None, type=None, start=1)
|
723,045 |
isort.api
|
check_code_string
|
Checks the order, format, and categorization of imports within the provided code string.
Returns `True` if everything is correct, otherwise `False`.
- **code**: The string of code with imports that need to be sorted.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
|
def check_code_string(
code: str,
show_diff: Union[bool, TextIO] = False,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
**config_kwargs: Any,
) -> bool:
"""Checks the order, format, and categorization of imports within the provided code string.
Returns `True` if everything is correct, otherwise `False`.
- **code**: The string of code with imports that need to be sorted.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
"""
config = _config(path=file_path, config=config, **config_kwargs)
return check_stream(
StringIO(code),
show_diff=show_diff,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
)
|
(code: str, show_diff: Union[bool, TextIO] = False, extension: Optional[str] = None, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, disregard_skip: bool = False, **config_kwargs: Any) -> bool
|
723,047 |
isort.api
|
check_stream
|
Checks any imports within the provided code stream, returning `False` if any unsorted or
incorrectly imports are found or `True` if no problems are identified.
- **input_stream**: The stream of code with imports that need to be sorted.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
|
def check_stream(
input_stream: TextIO,
show_diff: Union[bool, TextIO] = False,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
**config_kwargs: Any,
) -> bool:
"""Checks any imports within the provided code stream, returning `False` if any unsorted or
incorrectly imports are found or `True` if no problems are identified.
- **input_stream**: The stream of code with imports that need to be sorted.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
"""
config = _config(path=file_path, config=config, **config_kwargs)
if show_diff:
input_stream = StringIO(input_stream.read())
changed: bool = sort_stream(
input_stream=input_stream,
output_stream=Empty,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
)
printer = create_terminal_printer(
color=config.color_output, error=config.format_error, success=config.format_success
)
if not changed:
if config.verbose and not config.only_modified:
printer.success(f"{file_path or ''} Everything Looks Good!")
return True
printer.error(f"{file_path or ''} Imports are incorrectly sorted and/or formatted.")
if show_diff:
output_stream = StringIO()
input_stream.seek(0)
file_contents = input_stream.read()
sort_stream(
input_stream=StringIO(file_contents),
output_stream=output_stream,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
)
output_stream.seek(0)
show_unified_diff(
file_input=file_contents,
file_output=output_stream.read(),
file_path=file_path,
output=None if show_diff is True else show_diff,
color_output=config.color_output,
)
return False
|
(input_stream: <class 'TextIO'>, show_diff: Union[bool, TextIO] = False, extension: Optional[str] = None, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, disregard_skip: bool = False, **config_kwargs: Any) -> bool
|
723,048 |
isort.api
|
sort_code_string
|
Sorts any imports within the provided code string, returning a new string with them sorted.
- **code**: The string of code with imports that need to be sorted.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- ****config_kwargs**: Any config modifications.
|
def sort_code_string(
code: str,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
show_diff: Union[bool, TextIO] = False,
**config_kwargs: Any,
) -> str:
"""Sorts any imports within the provided code string, returning a new string with them sorted.
- **code**: The string of code with imports that need to be sorted.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- ****config_kwargs**: Any config modifications.
"""
input_stream = StringIO(code)
output_stream = StringIO()
config = _config(path=file_path, config=config, **config_kwargs)
sort_stream(
input_stream,
output_stream,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
show_diff=show_diff,
)
output_stream.seek(0)
return output_stream.read()
|
(code: str, extension: Optional[str] = None, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, disregard_skip: bool = False, show_diff: Union[bool, TextIO] = False, **config_kwargs: Any) -> str
|
723,052 |
isort.api
|
sort_file
|
Sorts and formats any groups of imports imports within the provided file or Path.
Returns `True` if the file has been changed, otherwise `False`.
- **filename**: The name or Path of the file to format.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **ask_to_apply**: If `True`, prompt before applying any changes.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **write_to_stdout**: If `True`, write to stdout instead of the input file.
- **output**: If a TextIO is provided, results will be written there rather than replacing
the original file content.
- ****config_kwargs**: Any config modifications.
|
def sort_file(
filename: Union[str, Path],
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = True,
ask_to_apply: bool = False,
show_diff: Union[bool, TextIO] = False,
write_to_stdout: bool = False,
output: Optional[TextIO] = None,
**config_kwargs: Any,
) -> bool:
"""Sorts and formats any groups of imports imports within the provided file or Path.
Returns `True` if the file has been changed, otherwise `False`.
- **filename**: The name or Path of the file to format.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **ask_to_apply**: If `True`, prompt before applying any changes.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- **write_to_stdout**: If `True`, write to stdout instead of the input file.
- **output**: If a TextIO is provided, results will be written there rather than replacing
the original file content.
- ****config_kwargs**: Any config modifications.
"""
file_config: Config = config
if "config_trie" in config_kwargs:
config_trie = config_kwargs.pop("config_trie", None)
if config_trie:
config_info = config_trie.search(filename)
if config.verbose:
print(f"{config_info[0]} used for file {filename}")
file_config = Config(**config_info[1])
with io.File.read(filename) as source_file:
actual_file_path = file_path or source_file.path
config = _config(path=actual_file_path, config=file_config, **config_kwargs)
changed: bool = False
try:
if write_to_stdout:
changed = sort_stream(
input_stream=source_file.stream,
output_stream=sys.stdout,
config=config,
file_path=actual_file_path,
disregard_skip=disregard_skip,
extension=extension,
)
else:
if output is None:
try:
if config.overwrite_in_place:
output_stream_context = _in_memory_output_stream_context()
else:
output_stream_context = _file_output_stream_context(
filename, source_file
)
with output_stream_context as output_stream:
changed = sort_stream(
input_stream=source_file.stream,
output_stream=output_stream,
config=config,
file_path=actual_file_path,
disregard_skip=disregard_skip,
extension=extension,
)
output_stream.seek(0)
if changed:
if show_diff or ask_to_apply:
source_file.stream.seek(0)
show_unified_diff(
file_input=source_file.stream.read(),
file_output=output_stream.read(),
file_path=actual_file_path,
output=None
if show_diff is True
else cast(TextIO, show_diff),
color_output=config.color_output,
)
if show_diff or (
ask_to_apply
and not ask_whether_to_apply_changes_to_file(
str(source_file.path)
)
):
return False
source_file.stream.close()
if config.overwrite_in_place:
output_stream.seek(0)
with source_file.path.open("w") as fs:
shutil.copyfileobj(output_stream, fs)
if changed:
if not config.overwrite_in_place:
tmp_file = _tmp_file(source_file)
tmp_file.replace(source_file.path)
if not config.quiet:
print(f"Fixing {source_file.path}")
finally:
try: # Python 3.8+: use `missing_ok=True` instead of try except.
if not config.overwrite_in_place: # pragma: no branch
tmp_file = _tmp_file(source_file)
tmp_file.unlink()
except FileNotFoundError:
pass # pragma: no cover
else:
changed = sort_stream(
input_stream=source_file.stream,
output_stream=output,
config=config,
file_path=actual_file_path,
disregard_skip=disregard_skip,
extension=extension,
)
if changed and show_diff:
source_file.stream.seek(0)
output.seek(0)
show_unified_diff(
file_input=source_file.stream.read(),
file_output=output.read(),
file_path=actual_file_path,
output=None if show_diff is True else show_diff,
color_output=config.color_output,
)
source_file.stream.close()
except ExistingSyntaxErrors:
warn(f"{actual_file_path} unable to sort due to existing syntax errors")
except IntroducedSyntaxErrors: # pragma: no cover
warn(f"{actual_file_path} unable to sort as isort introduces new syntax errors")
return changed
|
(filename: Union[str, pathlib.Path], extension: Optional[str] = None, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, disregard_skip: bool = True, ask_to_apply: bool = False, show_diff: Union[bool, TextIO] = False, write_to_stdout: bool = False, output: Optional[TextIO] = None, **config_kwargs: Any) -> bool
|
723,054 |
isort.api
|
find_imports_in_code
|
Finds and returns all imports within the provided code string.
- **code**: The string of code with imports that need to be sorted.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
|
def find_imports_in_code(
code: str,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
"""Finds and returns all imports within the provided code string.
- **code**: The string of code with imports that need to be sorted.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
"""
yield from find_imports_in_stream(
input_stream=StringIO(code),
config=config,
file_path=file_path,
unique=unique,
top_only=top_only,
**config_kwargs,
)
|
(code: str, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, unique: Union[bool, isort.api.ImportKey] = False, top_only: bool = False, **config_kwargs: Any) -> Iterator[isort.identify.Import]
|
723,055 |
isort.api
|
find_imports_in_file
|
Finds and returns all imports within the provided source file.
- **filename**: The name or Path of the file to look for imports in.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
|
def find_imports_in_file(
filename: Union[str, Path],
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
"""Finds and returns all imports within the provided source file.
- **filename**: The name or Path of the file to look for imports in.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
"""
with io.File.read(filename) as source_file:
yield from find_imports_in_stream(
input_stream=source_file.stream,
config=config,
file_path=file_path or source_file.path,
unique=unique,
top_only=top_only,
**config_kwargs,
)
|
(filename: Union[str, pathlib.Path], config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, unique: Union[bool, isort.api.ImportKey] = False, top_only: bool = False, **config_kwargs: Any) -> Iterator[isort.identify.Import]
|
723,056 |
isort.api
|
find_imports_in_paths
|
Finds and returns all imports within the provided source paths.
- **paths**: A collection of paths to recursively look for imports within.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
|
def find_imports_in_paths(
paths: Iterator[Union[str, Path]],
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
"""Finds and returns all imports within the provided source paths.
- **paths**: A collection of paths to recursively look for imports within.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- ****config_kwargs**: Any config modifications.
"""
config = _config(config=config, **config_kwargs)
seen: Optional[Set[str]] = set() if unique else None
yield from chain(
*(
find_imports_in_file(
file_name, unique=unique, config=config, top_only=top_only, _seen=seen
)
for file_name in files.find(map(str, paths), config, [], [])
)
)
|
(paths: Iterator[Union[str, pathlib.Path]], config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, unique: Union[bool, isort.api.ImportKey] = False, top_only: bool = False, **config_kwargs: Any) -> Iterator[isort.identify.Import]
|
723,057 |
isort.api
|
find_imports_in_stream
|
Finds and returns all imports within the provided code stream.
- **input_stream**: The stream of code with imports that need to be sorted.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- **_seen**: An optional set of imports already seen. Generally meant only for internal use.
- ****config_kwargs**: Any config modifications.
|
def find_imports_in_stream(
input_stream: TextIO,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
top_only: bool = False,
_seen: Optional[Set[str]] = None,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
"""Finds and returns all imports within the provided code stream.
- **input_stream**: The stream of code with imports that need to be sorted.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **unique**: If True, only the first instance of an import is returned.
- **top_only**: If True, only return imports that occur before the first function or class.
- **_seen**: An optional set of imports already seen. Generally meant only for internal use.
- ****config_kwargs**: Any config modifications.
"""
config = _config(config=config, **config_kwargs)
identified_imports = identify.imports(
input_stream, config=config, file_path=file_path, top_only=top_only
)
if not unique:
yield from identified_imports
seen: Set[str] = set() if _seen is None else _seen
for identified_import in identified_imports:
if unique in (True, ImportKey.ALIAS):
key = identified_import.statement()
elif unique == ImportKey.ATTRIBUTE:
key = f"{identified_import.module}.{identified_import.attribute}"
elif unique == ImportKey.MODULE:
key = identified_import.module
elif unique == ImportKey.PACKAGE: # pragma: no branch # type checking ensures this
key = identified_import.module.split(".")[0]
if key and key not in seen:
seen.add(key)
yield identified_import
|
(input_stream: <class 'TextIO'>, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, unique: Union[bool, isort.api.ImportKey] = False, top_only: bool = False, _seen: Optional[Set[str]] = None, **config_kwargs: Any) -> Iterator[isort.identify.Import]
|
723,065 |
isort.place
|
module
|
Returns the section placement for the given module name.
|
def module(name: str, config: Config = DEFAULT_CONFIG) -> str:
"""Returns the section placement for the given module name."""
return module_with_reason(name, config)[0]
|
(name: str, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False)) -> str
|
723,071 |
isort.api
|
sort_stream
|
Sorts any imports within the provided code stream, outputs to the provided output stream.
Returns `True` if anything is modified from the original input stream, otherwise `False`.
- **input_stream**: The stream of code with imports that need to be sorted.
- **output_stream**: The stream where sorted imports should be written to.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- ****config_kwargs**: Any config modifications.
|
def sort_stream(
input_stream: TextIO,
output_stream: TextIO,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
show_diff: Union[bool, TextIO] = False,
raise_on_skip: bool = True,
**config_kwargs: Any,
) -> bool:
"""Sorts any imports within the provided code stream, outputs to the provided output stream.
Returns `True` if anything is modified from the original input stream, otherwise `False`.
- **input_stream**: The stream of code with imports that need to be sorted.
- **output_stream**: The stream where sorted imports should be written to.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a
TextIO stream is provided results will be written to it, otherwise no diff will be computed.
- ****config_kwargs**: Any config modifications.
"""
extension = extension or (file_path and file_path.suffix.lstrip(".")) or "py"
if show_diff:
_output_stream = StringIO()
_input_stream = StringIO(input_stream.read())
changed = sort_stream(
input_stream=_input_stream,
output_stream=_output_stream,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
raise_on_skip=raise_on_skip,
**config_kwargs,
)
_output_stream.seek(0)
_input_stream.seek(0)
show_unified_diff(
file_input=_input_stream.read(),
file_output=_output_stream.read(),
file_path=file_path,
output=output_stream if show_diff is True else show_diff,
color_output=config.color_output,
)
return changed
config = _config(path=file_path, config=config, **config_kwargs)
content_source = str(file_path or "Passed in content")
if not disregard_skip and file_path and config.is_skipped(file_path):
raise FileSkipSetting(content_source)
_internal_output = output_stream
if config.atomic:
try:
file_content = input_stream.read()
compile(file_content, content_source, "exec", 0, 1)
except SyntaxError:
if extension not in CYTHON_EXTENSIONS:
raise ExistingSyntaxErrors(content_source)
if config.verbose:
warn(
f"{content_source} Python AST errors found but ignored due to Cython extension"
)
input_stream = StringIO(file_content)
if not output_stream.readable():
_internal_output = StringIO()
try:
changed = core.process(
input_stream,
_internal_output,
extension=extension,
config=config,
raise_on_skip=raise_on_skip,
)
except FileSkipComment:
raise FileSkipComment(content_source)
if config.atomic:
_internal_output.seek(0)
try:
compile(_internal_output.read(), content_source, "exec", 0, 1)
_internal_output.seek(0)
except SyntaxError: # pragma: no cover
if extension not in CYTHON_EXTENSIONS:
raise IntroducedSyntaxErrors(content_source)
if config.verbose:
warn(
f"{content_source} Python AST errors found but ignored due to Cython extension"
)
if _internal_output != output_stream:
output_stream.write(_internal_output.read())
return changed
|
(input_stream: <class 'TextIO'>, output_stream: <class 'TextIO'>, extension: Optional[str] = None, config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent=' ', comment_prefix=' #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'dist', '.tox', '.mypy_cache', '_build', '.git', '.direnv', '.venv', '.nox', 'buck-out', '.eggs', '__pypackages__', '.pytype', '.svn', '.bzr', '.hg', '.pants.d', 'build', 'venv', 'node_modules'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'ssl', 'pprint', 'sre_constants', 'tkinter', 'modulefinder', 'mmap', 'grp', 'ipaddress', 'optparse', 'select', 'dis', 'fnmatch', 'sunau', 'csv', 'calendar', 'sys', 'cgi', 'signal', 'selectors', 'logging', 'traceback', 'spwd', 'audioop', 'difflib', 'imghdr', 'codecs', 'types', 'py_compile', 'dbm', 'warnings', 'abc', 'glob', 'asynchat', 'timeit', 'tracemalloc', 'fpectl', 'token', 'fileinput', 'contextvars', 'aifc', 'graphlib', 'plistlib', 'asyncio', 'hashlib', 'zipapp', 'cProfile', 'getpass', 'msilib', 'itertools', 'unicodedata', 'cgitb', 'http', 'syslog', 'struct', 'platform', 'gzip', 'symtable', 'filecmp', 'getopt', 'operator', 'statistics', 'math', 'pathlib', 'asyncore', 'pstats', 'webbrowser', 'smtplib', 'shelve', 'termios', 'sre', 'unittest', 'winreg', 'binhex', 'array', 'configparser', 'fractions', 'chunk', 'symbol', 'socket', 're', 'lib2to3', 'ntpath', 'copy', 'bisect', 'cmd', 'turtle', 'turtledemo', 'xmlrpc', 'argparse', 'doctest', 'pydoc', 'weakref', 'poplib', 'encodings', 'bz2', 'builtins', 'lzma', 'winsound', 'decimal', 'xdrlib', 'sqlite3', 'socketserver', 'telnetlib', 'ossaudiodev', 'xml', 'faulthandler', 'fcntl', 'random', 'wsgiref', 'numbers', 'inspect', 'mailbox', 'posixpath', 'resource', 'trace', 'dataclasses', 'zlib', 'errno', 'tty', 'multiprocessing', 'io', 'ftplib', 'runpy', 'threading', 'usercustomize', 'idlelib', 'mimetypes', '_tkinter', 'profile', 'readline', 'gc', 'zipimport', 'textwrap', 'bdb', '_dummy_thread', 'posix', 'atexit', 'pkgutil', 'concurrent', 'rlcompleter', 'site', 'os', 'string', 'linecache', 'heapq', 'sndhdr', 'zipfile', 'sitecustomize', 'sysconfig', 'datetime', 'pickle', 'sre_parse', 'ast', 'codeop', 'dummy_threading', 'reprlib', 'sre_compile', 'ensurepip', 'shlex', 'shutil', 'keyword', 'smtpd', 'mailcap', 'queue', 'time', 'quopri', 'imaplib', 'copyreg', 'crypt', 'collections', 'compileall', 'pipes', 'venv', 'stringprep', 'imp', 'ctypes', 'pty', 'formatter', 'test', 'email', 'tabnanny', 'typing', 'urllib', 'html', 'parser', 'code', 'contextlib', 'tempfile', 'sched', 'subprocess', 'tarfile', 'secrets', 'colorsys', 'tokenize', 'wave', 'pdb', 'msvcrt', 'uuid', 'marshal', 'functools', 'base64', 'importlib', 'curses', 'uu', '_thread', 'binascii', 'locale', 'zoneinfo', 'netrc', 'tomllib', 'cmath', 'hmac', 'stat', 'pwd', 'enum', 'nis', '_ast', 'json', 'pickletools', 'gettext', 'distutils', 'macpath', 'nntplib', 'pyclbr'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': ' ', 'comment_prefix': ' #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'pyx', 'pyi', 'pxd', 'py'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/app', profile='', honor_noqa=False, src_paths=(PosixPath('/app/src'), PosixPath('/app')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'pyx', 'pyi', 'pxd', 'py'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False), file_path: Optional[pathlib.Path] = None, disregard_skip: bool = False, show_diff: Union[bool, TextIO] = False, raise_on_skip: bool = True, **config_kwargs: Any) -> bool
|
723,075 |
mathprimes
|
_is_prime
|
Returns whether or not an integer is prime.
Uses the fact that all prime numbers except two and three are one more or one less than a multiple of six.
The checks whether a given list of smaller primes are factors.
If not then the number is prime.
|
def _is_prime(i: int, prev: Tuple[int]) -> bool:
"""
Returns whether or not an integer is prime.
Uses the fact that all prime numbers except two and three are one more or one less than a multiple of six.
The checks whether a given list of smaller primes are factors.
If not then the number is prime.
"""
if i in {0,1}:
return False
if i in {2,3}:
return True
if (i - 1) % 6 == 0 or (i + 1) % 6 == 0:
for j in prev:
if i % j == 0:
return False
return True
return False
|
(i: int, prev: Tuple[int]) -> bool
|
723,076 |
mathprimes
|
is_prime
|
A function that implents ``_is_prime`` from above but will auto generate primes if not given.
|
def is_prime(number: int, primes = None) -> bool:
"""A function that implents ``_is_prime`` from above but will auto generate primes if not given."""
if primes is None:
for i, primes in prime_gen():
if i >= number:
break
return number in primes
|
(number: int, primes=None) -> bool
|
723,077 |
mathprimes
|
prime_factorization
|
Given any integer and an optional iterable of primes.
Returns a dictionary of the prime factors and their occurences.
|
def prime_factorization(number: int, primes = None):
"""
Given any integer and an optional iterable of primes.
Returns a dictionary of the prime factors and their occurences.
"""
if number <= 1:
return None
# If primes is not given autogenerate them.
if primes is None:
for i, primes in prime_gen():
if i >= number:
break
for prime in primes:
if number % prime == 0:
if (next_number := number // prime) == 1:
return {prime: 1}
result = prime_factorization(next_number, primes)
if result.get(prime):
result[prime] += 1
else:
result[prime] = 1
return result
raise ValueError(f"Not supposed to happen? {number}")
|
(number: int, primes=None)
|
723,078 |
mathprimes
|
prime_gen
|
An infinite generator yielding a tuple of ``(prime_number, previous_prime_numbers)``
|
def prime_gen() -> Generator[Tuple[int,Tuple[int]], None, None]:
"""An infinite generator yielding a tuple of ``(prime_number, previous_prime_numbers)``"""
primes = ()
i = 2
while True:
if _is_prime(i, primes):
primes += (i,)
yield i, primes
i += 1
|
() -> Generator[Tuple[int, Tuple[int]], NoneType, NoneType]
|
723,263 |
exponent_server_sdk
|
DeviceNotRegisteredError
|
Raised when the push token is invalid
To handle this error, you should stop sending messages to this token.
|
class DeviceNotRegisteredError(PushTicketError):
"""Raised when the push token is invalid
To handle this error, you should stop sending messages to this token.
"""
pass
|
(push_response)
|
723,264 |
exponent_server_sdk
|
__init__
| null |
def __init__(self, push_response):
if push_response.message:
self.message = push_response.message
else:
self.message = 'Unknown push ticket error'
super(PushTicketError, self).__init__(self.message)
self.push_response = push_response
|
(self, push_response)
|
723,265 |
exponent_server_sdk
|
InvalidCredentialsError
|
Raised when our push notification credentials for your standalone app
are invalid (ex: you may have revoked them).
Run expo build:ios -c to regenerate new push notification credentials for
iOS. If you revoke an APN key, all apps that rely on that key will no
longer be able to send or receive push notifications until you upload a
new key to replace it. Uploading a new APN key will not change your users'
Expo Push Tokens.
|
class InvalidCredentialsError(PushTicketError):
"""Raised when our push notification credentials for your standalone app
are invalid (ex: you may have revoked them).
Run expo build:ios -c to regenerate new push notification credentials for
iOS. If you revoke an APN key, all apps that rely on that key will no
longer be able to send or receive push notifications until you upload a
new key to replace it. Uploading a new APN key will not change your users'
Expo Push Tokens.
"""
pass
|
(push_response)
|
723,267 |
exponent_server_sdk
|
MessageRateExceededError
|
Raised when you are sending messages too frequently to a device
You should implement exponential backoff and slowly retry sending messages.
|
class MessageRateExceededError(PushTicketError):
"""Raised when you are sending messages too frequently to a device
You should implement exponential backoff and slowly retry sending messages.
"""
pass
|
(push_response)
|
723,269 |
exponent_server_sdk
|
MessageTooBigError
|
Raised when the notification was too large.
On Android and iOS, the total payload must be at most 4096 bytes.
|
class MessageTooBigError(PushTicketError):
"""Raised when the notification was too large.
On Android and iOS, the total payload must be at most 4096 bytes.
"""
pass
|
(push_response)
|
723,271 |
exponent_server_sdk
|
PushClient
|
Exponent push client
See full API docs at https://docs.expo.io/versions/latest/guides/push-notifications.html#http2-api
|
class PushClient(object):
"""Exponent push client
See full API docs at https://docs.expo.io/versions/latest/guides/push-notifications.html#http2-api
"""
DEFAULT_HOST = "https://exp.host"
DEFAULT_BASE_API_URL = "/--/api/v2"
DEFAULT_MAX_MESSAGE_COUNT = 100
DEFAULT_MAX_RECEIPT_COUNT = 1000
def __init__(self, host=None, api_url=None, session=None, force_fcm_v1=None, **kwargs):
"""Construct a new PushClient object.
Args:
host: The server protocol, hostname, and port.
api_url: The api url at the host.
session: Pass in your own requests.Session object if you prefer
to customize
force_fcm_v1: If True, send Android notifications via FCM V1, regardless
of whether a valid credential exists.
"""
self.host = host
if not self.host:
self.host = PushClient.DEFAULT_HOST
self.api_url = api_url
if not self.api_url:
self.api_url = PushClient.DEFAULT_BASE_API_URL
self.force_fcm_v1 = force_fcm_v1
self.max_message_count = kwargs[
'max_message_count'] if 'max_message_count' in kwargs else PushClient.DEFAULT_MAX_MESSAGE_COUNT
self.max_receipt_count = kwargs[
'max_receipt_count'] if 'max_receipt_count' in kwargs else PushClient.DEFAULT_MAX_RECEIPT_COUNT
self.timeout = kwargs['timeout'] if 'timeout' in kwargs else None
self.session = session
if not self.session:
self.session = requests.Session()
self.session.headers.update({
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
})
@classmethod
def is_exponent_push_token(cls, token):
"""Returns `True` if the token is an Exponent push token"""
import six
return (isinstance(token, six.string_types)
and token.startswith('ExponentPushToken'))
def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects.
"""
url = urljoin(self.host, self.api_url + '/push/send')
if self.force_fcm_v1 is not None:
query_params = {'useFcmV1': 'true' if self.force_fcm_v1 else 'false'}
url += '?' + urlencode(query_params)
response = self.session.post(
url,
data=json.dumps([pm.get_payload() for pm in push_messages]),
timeout=self.timeout)
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError('Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError('Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# Sanity check the response
if len(push_messages) != len(response_data['data']):
raise PushServerError(
('Mismatched response length. Expected %d %s but only '
'received %d' %
(len(push_messages), 'receipt' if len(push_messages) == 1 else
'receipts', len(response_data['data']))),
response,
response_data=response_data)
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses(push_tickets) per push notification.
push_tickets = []
for i, push_ticket in enumerate(response_data['data']):
push_tickets.append(
PushTicket(
push_message=push_messages[i],
# If there is no status, assume error.
status=push_ticket.get('status', PushTicket.ERROR_STATUS),
message=push_ticket.get('message', ''),
details=push_ticket.get('details', None),
id=push_ticket.get('id', '')))
return push_tickets
def publish(self, push_message):
"""Sends a single push notification
Args:
push_message: A single PushMessage object.
Returns:
A PushTicket object which contains the results.
"""
return self.publish_multiple([push_message])[0]
def publish_multiple(self, push_messages):
"""Sends multiple push notifications at once
Args:
push_messages: An array of PushMessage objects.
Returns:
An array of PushTicket objects which contains the results.
"""
push_tickets = []
for start in itertools.count(0, self.max_message_count):
chunk = list(
itertools.islice(push_messages, start,
start + self.max_message_count))
if not chunk:
break
push_tickets.extend(self._publish_internal(chunk))
return push_tickets
def check_receipts_multiple(self, push_tickets):
"""
Check receipts in batches of 1000 as per expo docs
"""
receipts = []
for start in itertools.count(0, self.max_receipt_count):
chunk = list(
itertools.islice(push_tickets, start,
start + self.max_receipt_count))
if not chunk:
break
receipts.extend(self._check_receipts_internal(chunk))
return receipts
def _check_receipts_internal(self, push_tickets):
"""
Helper function for check_receipts_multiple
"""
response = self.session.post(
self.host + self.api_url + '/push/getReceipts',
json={'ids': [push_ticket.id for push_ticket in push_tickets]},
timeout=self.timeout)
receipts = self.validate_and_get_receipts(response)
return receipts
def check_receipts(self, push_tickets):
""" Checks the push receipts of the given push tickets """
# Delayed import because this file is immediately read on install, and
# the requests library may not be installed yet.
response = requests.post(
self.host + self.api_url + '/push/getReceipts',
data=json.dumps(
{'ids': [push_ticket.id for push_ticket in push_tickets]}),
headers={
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
},
timeout=self.timeout)
receipts = self.validate_and_get_receipts(response)
return receipts
def validate_and_get_receipts(self, response):
"""
Validate and get receipts for requests
"""
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError('Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError('Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses per push notification.
response_data = response_data['data']
ret = []
for r_id, val in response_data.items():
ret.append(
PushTicket(push_message=PushMessage(),
status=val.get('status', PushTicket.ERROR_STATUS),
message=val.get('message', ''),
details=val.get('details', None),
id=r_id))
return ret
|
(host=None, api_url=None, session=None, force_fcm_v1=None, **kwargs)
|
723,272 |
exponent_server_sdk
|
__init__
|
Construct a new PushClient object.
Args:
host: The server protocol, hostname, and port.
api_url: The api url at the host.
session: Pass in your own requests.Session object if you prefer
to customize
force_fcm_v1: If True, send Android notifications via FCM V1, regardless
of whether a valid credential exists.
|
def __init__(self, host=None, api_url=None, session=None, force_fcm_v1=None, **kwargs):
"""Construct a new PushClient object.
Args:
host: The server protocol, hostname, and port.
api_url: The api url at the host.
session: Pass in your own requests.Session object if you prefer
to customize
force_fcm_v1: If True, send Android notifications via FCM V1, regardless
of whether a valid credential exists.
"""
self.host = host
if not self.host:
self.host = PushClient.DEFAULT_HOST
self.api_url = api_url
if not self.api_url:
self.api_url = PushClient.DEFAULT_BASE_API_URL
self.force_fcm_v1 = force_fcm_v1
self.max_message_count = kwargs[
'max_message_count'] if 'max_message_count' in kwargs else PushClient.DEFAULT_MAX_MESSAGE_COUNT
self.max_receipt_count = kwargs[
'max_receipt_count'] if 'max_receipt_count' in kwargs else PushClient.DEFAULT_MAX_RECEIPT_COUNT
self.timeout = kwargs['timeout'] if 'timeout' in kwargs else None
self.session = session
if not self.session:
self.session = requests.Session()
self.session.headers.update({
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
})
|
(self, host=None, api_url=None, session=None, force_fcm_v1=None, **kwargs)
|
723,273 |
exponent_server_sdk
|
_check_receipts_internal
|
Helper function for check_receipts_multiple
|
def _check_receipts_internal(self, push_tickets):
"""
Helper function for check_receipts_multiple
"""
response = self.session.post(
self.host + self.api_url + '/push/getReceipts',
json={'ids': [push_ticket.id for push_ticket in push_tickets]},
timeout=self.timeout)
receipts = self.validate_and_get_receipts(response)
return receipts
|
(self, push_tickets)
|
723,274 |
exponent_server_sdk
|
_publish_internal
|
Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects.
|
def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects.
"""
url = urljoin(self.host, self.api_url + '/push/send')
if self.force_fcm_v1 is not None:
query_params = {'useFcmV1': 'true' if self.force_fcm_v1 else 'false'}
url += '?' + urlencode(query_params)
response = self.session.post(
url,
data=json.dumps([pm.get_payload() for pm in push_messages]),
timeout=self.timeout)
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError('Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError('Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# Sanity check the response
if len(push_messages) != len(response_data['data']):
raise PushServerError(
('Mismatched response length. Expected %d %s but only '
'received %d' %
(len(push_messages), 'receipt' if len(push_messages) == 1 else
'receipts', len(response_data['data']))),
response,
response_data=response_data)
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses(push_tickets) per push notification.
push_tickets = []
for i, push_ticket in enumerate(response_data['data']):
push_tickets.append(
PushTicket(
push_message=push_messages[i],
# If there is no status, assume error.
status=push_ticket.get('status', PushTicket.ERROR_STATUS),
message=push_ticket.get('message', ''),
details=push_ticket.get('details', None),
id=push_ticket.get('id', '')))
return push_tickets
|
(self, push_messages)
|
723,275 |
exponent_server_sdk
|
check_receipts
|
Checks the push receipts of the given push tickets
|
def check_receipts(self, push_tickets):
""" Checks the push receipts of the given push tickets """
# Delayed import because this file is immediately read on install, and
# the requests library may not be installed yet.
response = requests.post(
self.host + self.api_url + '/push/getReceipts',
data=json.dumps(
{'ids': [push_ticket.id for push_ticket in push_tickets]}),
headers={
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
},
timeout=self.timeout)
receipts = self.validate_and_get_receipts(response)
return receipts
|
(self, push_tickets)
|
723,276 |
exponent_server_sdk
|
check_receipts_multiple
|
Check receipts in batches of 1000 as per expo docs
|
def check_receipts_multiple(self, push_tickets):
"""
Check receipts in batches of 1000 as per expo docs
"""
receipts = []
for start in itertools.count(0, self.max_receipt_count):
chunk = list(
itertools.islice(push_tickets, start,
start + self.max_receipt_count))
if not chunk:
break
receipts.extend(self._check_receipts_internal(chunk))
return receipts
|
(self, push_tickets)
|
723,277 |
exponent_server_sdk
|
publish
|
Sends a single push notification
Args:
push_message: A single PushMessage object.
Returns:
A PushTicket object which contains the results.
|
def publish(self, push_message):
"""Sends a single push notification
Args:
push_message: A single PushMessage object.
Returns:
A PushTicket object which contains the results.
"""
return self.publish_multiple([push_message])[0]
|
(self, push_message)
|
723,278 |
exponent_server_sdk
|
publish_multiple
|
Sends multiple push notifications at once
Args:
push_messages: An array of PushMessage objects.
Returns:
An array of PushTicket objects which contains the results.
|
def publish_multiple(self, push_messages):
"""Sends multiple push notifications at once
Args:
push_messages: An array of PushMessage objects.
Returns:
An array of PushTicket objects which contains the results.
"""
push_tickets = []
for start in itertools.count(0, self.max_message_count):
chunk = list(
itertools.islice(push_messages, start,
start + self.max_message_count))
if not chunk:
break
push_tickets.extend(self._publish_internal(chunk))
return push_tickets
|
(self, push_messages)
|
723,279 |
exponent_server_sdk
|
validate_and_get_receipts
|
Validate and get receipts for requests
|
def validate_and_get_receipts(self, response):
"""
Validate and get receipts for requests
"""
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError('Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError('Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses per push notification.
response_data = response_data['data']
ret = []
for r_id, val in response_data.items():
ret.append(
PushTicket(push_message=PushMessage(),
status=val.get('status', PushTicket.ERROR_STATUS),
message=val.get('message', ''),
details=val.get('details', None),
id=r_id))
return ret
|
(self, response)
|
723,280 |
exponent_server_sdk
|
PushMessage
|
An object that describes a push notification request.
You can override this class to provide your own custom validation before
sending these to the Exponent push servers. You can also override the
get_payload function itself to take advantage of any hidden or new
arguments before this library updates upstream.
Args:
to: A token of the form ExponentPushToken[xxxxxxx]
data: A dict of extra data to pass inside of the push notification.
The total notification payload must be at most 4096 bytes.
title: The title to display in the notification. On iOS, this is
displayed only on Apple Watch.
body: The message to display in the notification.
sound: A sound to play when the recipient receives this
notification. Specify "default" to play the device's default
notification sound, or omit this field to play no sound.
ttl: The number of seconds for which the message may be kept around
for redelivery if it hasn't been delivered yet. Defaults to 0.
expiration: UNIX timestamp for when this message expires. It has
the same effect as ttl, and is just an absolute timestamp
instead of a relative one.
priority: Delivery priority of the message. 'default', 'normal',
and 'high' are the only valid values.
badge: An integer representing the unread notification count. This
currently only affects iOS. Specify 0 to clear the badge count.
category: ID of the Notification Category through which to display
this notification.
channel_id: ID of the Notification Channel through which to display
this notification on Android devices.
display_in_foreground: Displays the notification when the app is
foregrounded. Defaults to `false`. No longer available?
subtitle: The subtitle to display in the notification below the
title (iOS only).
mutable_content: Specifies whether this notification can be
intercepted by the client app. In Expo Go, defaults to true.
In standalone and bare apps, defaults to false. (iOS Only)
|
class PushMessage(
namedtuple('PushMessage', [
'to', 'data', 'title', 'body', 'sound', 'ttl', 'expiration',
'priority', 'badge', 'category', 'display_in_foreground',
'channel_id', 'subtitle', 'mutable_content'
])):
"""An object that describes a push notification request.
You can override this class to provide your own custom validation before
sending these to the Exponent push servers. You can also override the
get_payload function itself to take advantage of any hidden or new
arguments before this library updates upstream.
Args:
to: A token of the form ExponentPushToken[xxxxxxx]
data: A dict of extra data to pass inside of the push notification.
The total notification payload must be at most 4096 bytes.
title: The title to display in the notification. On iOS, this is
displayed only on Apple Watch.
body: The message to display in the notification.
sound: A sound to play when the recipient receives this
notification. Specify "default" to play the device's default
notification sound, or omit this field to play no sound.
ttl: The number of seconds for which the message may be kept around
for redelivery if it hasn't been delivered yet. Defaults to 0.
expiration: UNIX timestamp for when this message expires. It has
the same effect as ttl, and is just an absolute timestamp
instead of a relative one.
priority: Delivery priority of the message. 'default', 'normal',
and 'high' are the only valid values.
badge: An integer representing the unread notification count. This
currently only affects iOS. Specify 0 to clear the badge count.
category: ID of the Notification Category through which to display
this notification.
channel_id: ID of the Notification Channel through which to display
this notification on Android devices.
display_in_foreground: Displays the notification when the app is
foregrounded. Defaults to `false`. No longer available?
subtitle: The subtitle to display in the notification below the
title (iOS only).
mutable_content: Specifies whether this notification can be
intercepted by the client app. In Expo Go, defaults to true.
In standalone and bare apps, defaults to false. (iOS Only)
"""
def get_payload(self):
# Sanity check for invalid push token format.
if not PushClient.is_exponent_push_token(self.to):
raise ValueError('Invalid push token')
# There is only one required field.
payload = {
'to': self.to,
}
# All of these fields are optional.
if self.data is not None:
payload['data'] = self.data
if self.title is not None:
payload['title'] = self.title
if self.body is not None:
payload['body'] = self.body
if self.ttl is not None:
payload['ttl'] = self.ttl
if self.expiration is not None:
payload['expiration'] = self.expiration
if self.priority is not None:
payload['priority'] = self.priority
if self.subtitle is not None:
payload['subtitle'] = self.subtitle
if self.sound is not None:
payload['sound'] = self.sound
if self.badge is not None:
payload['badge'] = self.badge
if self.channel_id is not None:
payload['channelId'] = self.channel_id
if self.category is not None:
payload['categoryId'] = self.category
if self.mutable_content is not None:
payload['mutableContent'] = self.mutable_content
# here for legacy reasons
if self.display_in_foreground is not None:
payload['_displayInForeground'] = self.display_in_foreground
return payload
|
(to=None, data=None, title=None, body=None, sound=None, ttl=None, expiration=None, priority=None, badge=None, category=None, display_in_foreground=None, channel_id=None, subtitle=None, mutable_content=None)
|
723,282 |
namedtuple_PushMessage
|
__new__
|
Create new instance of PushMessage(to, data, title, body, sound, ttl, expiration, priority, badge, category, display_in_foreground, channel_id, subtitle, mutable_content)
|
from builtins import function
|
(_cls, to=None, data=None, title=None, body=None, sound=None, ttl=None, expiration=None, priority=None, badge=None, category=None, display_in_foreground=None, channel_id=None, subtitle=None, mutable_content=None)
|
723,285 |
collections
|
_replace
|
Return a new PushMessage object replacing specified fields with new values
|
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
|
(self, /, **kwds)
|
723,286 |
exponent_server_sdk
|
get_payload
| null |
def get_payload(self):
# Sanity check for invalid push token format.
if not PushClient.is_exponent_push_token(self.to):
raise ValueError('Invalid push token')
# There is only one required field.
payload = {
'to': self.to,
}
# All of these fields are optional.
if self.data is not None:
payload['data'] = self.data
if self.title is not None:
payload['title'] = self.title
if self.body is not None:
payload['body'] = self.body
if self.ttl is not None:
payload['ttl'] = self.ttl
if self.expiration is not None:
payload['expiration'] = self.expiration
if self.priority is not None:
payload['priority'] = self.priority
if self.subtitle is not None:
payload['subtitle'] = self.subtitle
if self.sound is not None:
payload['sound'] = self.sound
if self.badge is not None:
payload['badge'] = self.badge
if self.channel_id is not None:
payload['channelId'] = self.channel_id
if self.category is not None:
payload['categoryId'] = self.category
if self.mutable_content is not None:
payload['mutableContent'] = self.mutable_content
# here for legacy reasons
if self.display_in_foreground is not None:
payload['_displayInForeground'] = self.display_in_foreground
return payload
|
(self)
|
723,287 |
exponent_server_sdk
|
PushReceipt
|
Wrapper class for a PushReceipt response. Similar to a PushResponse
A successful single push notification:
'data': {
'id': {'status': 'ok'}
}
Errors contain 'errors'
|
class PushReceipt(
namedtuple('PushReceipt', ['id', 'status', 'message', 'details'])):
"""Wrapper class for a PushReceipt response. Similar to a PushResponse
A successful single push notification:
'data': {
'id': {'status': 'ok'}
}
Errors contain 'errors'
"""
# Known status codes
ERROR_STATUS = 'error'
SUCCESS_STATUS = 'ok'
# Known error strings
ERROR_DEVICE_NOT_REGISTERED = 'DeviceNotRegistered'
ERROR_MESSAGE_TOO_BIG = 'MessageTooBig'
ERROR_MESSAGE_RATE_EXCEEDED = 'MessageRateExceeded'
INVALID_CREDENTIALS = 'InvalidCredentials'
def is_success(self):
"""Returns True if this push notification successfully sent."""
return self.status == PushReceipt.SUCCESS_STATUS
def validate_response(self):
"""Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
"""
if self.is_success():
return
# Handle the error if we have any information
if self.details:
error = self.details.get('error', None)
if error == PushReceipt.ERROR_DEVICE_NOT_REGISTERED:
raise DeviceNotRegisteredError(self)
elif error == PushReceipt.ERROR_MESSAGE_TOO_BIG:
raise MessageTooBigError(self)
elif error == PushReceipt.ERROR_MESSAGE_RATE_EXCEEDED:
raise MessageRateExceededError(self)
elif error == PushReceipt.INVALID_CREDENTIALS:
raise InvalidCredentialsError(self)
# No known error information, so let's raise a generic error.
raise PushTicketError(self)
|
(id, status, message, details)
|
723,289 |
namedtuple_PushReceipt
|
__new__
|
Create new instance of PushReceipt(id, status, message, details)
|
from builtins import function
|
(_cls, id, status, message, details)
|
723,292 |
collections
|
_replace
|
Return a new PushReceipt object replacing specified fields with new values
|
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
|
(self, /, **kwds)
|
723,293 |
exponent_server_sdk
|
is_success
|
Returns True if this push notification successfully sent.
|
def is_success(self):
"""Returns True if this push notification successfully sent."""
return self.status == PushReceipt.SUCCESS_STATUS
|
(self)
|
723,294 |
exponent_server_sdk
|
validate_response
|
Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
|
def validate_response(self):
"""Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
"""
if self.is_success():
return
# Handle the error if we have any information
if self.details:
error = self.details.get('error', None)
if error == PushReceipt.ERROR_DEVICE_NOT_REGISTERED:
raise DeviceNotRegisteredError(self)
elif error == PushReceipt.ERROR_MESSAGE_TOO_BIG:
raise MessageTooBigError(self)
elif error == PushReceipt.ERROR_MESSAGE_RATE_EXCEEDED:
raise MessageRateExceededError(self)
elif error == PushReceipt.INVALID_CREDENTIALS:
raise InvalidCredentialsError(self)
# No known error information, so let's raise a generic error.
raise PushTicketError(self)
|
(self)
|
723,295 |
exponent_server_sdk
|
PushServerError
|
Raised when the push token server is not behaving as expected
For example, invalid push notification arguments result in a different
style of error. Instead of a "data" array containing errors per
notification, an "error" array is returned.
{"errors": [
{"code": "API_ERROR",
"message": "child "to" fails because ["to" must be a string]. "value" must be an array."
}
]}
|
class PushServerError(Exception):
"""Raised when the push token server is not behaving as expected
For example, invalid push notification arguments result in a different
style of error. Instead of a "data" array containing errors per
notification, an "error" array is returned.
{"errors": [
{"code": "API_ERROR",
"message": "child \"to\" fails because [\"to\" must be a string]. \"value\" must be an array."
}
]}
"""
def __init__(self, message, response, response_data=None, errors=None):
self.message = message
self.response = response
self.response_data = response_data
self.errors = errors
super(PushServerError, self).__init__(self.message)
|
(message, response, response_data=None, errors=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.