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
18,268
builtins
traceback
TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno) -- Create a new traceback object.
from builtins import traceback
null
18,269
yarl
URL
null
from yarl import URL
(val='', *, encoded=False, strict=None)
18,270
yarl._url
__bool__
null
def __bool__(self) -> bool: return bool( self._val.netloc or self._val.path or self._val.query or self._val.fragment )
(self) -> bool
18,271
yarl._url
__bytes__
null
def __bytes__(self): return str(self).encode("ascii")
(self)
18,272
yarl._url
__eq__
null
def __eq__(self, other): if not type(other) is URL: return NotImplemented val1 = self._val if not val1.path and self.is_absolute(): val1 = val1._replace(path="/") val2 = other._val if not val2.path and other.is_absolute(): val2 = val2._replace(path="/") return val1 == val2
(self, other)
18,273
yarl._url
__ge__
null
def __ge__(self, other): if not type(other) is URL: return NotImplemented return self._val >= other._val
(self, other)
18,274
yarl._url
__getstate__
null
def __getstate__(self): return (self._val,)
(self)
18,275
yarl._url
__gt__
null
def __gt__(self, other): if not type(other) is URL: return NotImplemented return self._val > other._val
(self, other)
18,276
yarl._url
__hash__
null
def __hash__(self): ret = self._cache.get("hash") if ret is None: val = self._val if not val.path and self.is_absolute(): val = val._replace(path="/") ret = self._cache["hash"] = hash(val) return ret
(self)
18,277
yarl._url
__le__
null
def __le__(self, other): if not type(other) is URL: return NotImplemented return self._val <= other._val
(self, other)
18,278
yarl._url
__lt__
null
def __lt__(self, other): if not type(other) is URL: return NotImplemented return self._val < other._val
(self, other)
18,279
yarl._url
__mod__
null
def __mod__(self, query): return self.update_query(query)
(self, query)
18,280
yarl._url
__new__
null
def __new__(cls, val="", *, encoded=False, strict=None): if strict is not None: # pragma: no cover warnings.warn("strict parameter is ignored") if type(val) is cls: return val if type(val) is str: val = urlsplit(val) elif type(val) is SplitResult: if not encoded: raise ValueError("Cannot apply decoding to SplitResult") elif isinstance(val, str): val = urlsplit(str(val)) else: raise TypeError("Constructor parameter should be str") if not encoded: if not val[1]: # netloc netloc = "" host = "" else: host = val.hostname if host is None: raise ValueError("Invalid URL: host is required for absolute urls") try: port = val.port except ValueError as e: raise ValueError( "Invalid URL: port can't be converted to integer" ) from e netloc = cls._make_netloc( val.username, val.password, host, port, encode=True, requote=True ) path = cls._PATH_REQUOTER(val[2]) if netloc: path = cls._normalize_path(path) cls._validate_authority_uri_abs_path(host=host, path=path) query = cls._QUERY_REQUOTER(val[3]) fragment = cls._FRAGMENT_REQUOTER(val[4]) val = SplitResult(val[0], netloc, path, query, fragment) self = object.__new__(cls) self._val = val self._cache = {} return self
(cls, val='', *, encoded=False, strict=None)
18,281
yarl._url
__repr__
null
def __repr__(self): return f"{self.__class__.__name__}('{str(self)}')"
(self)
18,282
yarl._url
__setstate__
null
def __setstate__(self, state): if state[0] is None and isinstance(state[1], dict): # default style pickle self._val = state[1]["_val"] else: self._val, *unused = state self._cache = {}
(self, state)
18,283
yarl._url
__str__
null
def __str__(self): val = self._val if not val.path and self.is_absolute() and (val.query or val.fragment): val = val._replace(path="/") return urlunsplit(val)
(self)
18,284
yarl._url
__truediv__
null
def __truediv__(self, name): if not isinstance(name, str): return NotImplemented return self._make_child((str(name),))
(self, name)
18,285
yarl._url
_get_str_query
null
def _get_str_query(self, *args, **kwargs): if kwargs: if len(args) > 0: raise ValueError( "Either kwargs or single query parameter must be present" ) query = kwargs elif len(args) == 1: query = args[0] else: raise ValueError("Either kwargs or single query parameter must be present") if query is None: query = None elif isinstance(query, Mapping): quoter = self._QUERY_PART_QUOTER query = "&".join(self._query_seq_pairs(quoter, query.items())) elif isinstance(query, str): query = self._QUERY_QUOTER(query) elif isinstance(query, (bytes, bytearray, memoryview)): raise TypeError( "Invalid query type: bytes, bytearray and memoryview are forbidden" ) elif isinstance(query, Sequence): quoter = self._QUERY_PART_QUOTER # We don't expect sequence values if we're given a list of pairs # already; only mappings like builtin `dict` which can't have the # same key pointing to multiple values are allowed to use # `_query_seq_pairs`. query = "&".join( quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query ) else: raise TypeError( "Invalid query type: only str, mapping or " "sequence of (key, value) pairs is allowed" ) return query
(self, *args, **kwargs)
18,286
yarl._url
_make_child
add segments to self._val.path, accounting for absolute vs relative paths
def _make_child(self, segments, encoded=False): """add segments to self._val.path, accounting for absolute vs relative paths""" # keep the trailing slash if the last segment ends with / parsed = [""] if segments and segments[-1][-1:] == "/" else [] for seg in reversed(segments): if not seg: continue if seg[0] == "/": raise ValueError( f"Appending path {seg!r} starting from slash is forbidden" ) seg = seg if encoded else self._PATH_QUOTER(seg) if "/" in seg: parsed += ( sub for sub in reversed(seg.split("/")) if sub and sub != "." ) elif seg != ".": parsed.append(seg) parsed.reverse() old_path = self._val.path if old_path: parsed = [*old_path.rstrip("/").split("/"), *parsed] if self.is_absolute(): parsed = _normalize_path_segments(parsed) if parsed and parsed[0] != "": # inject a leading slash when adding a path to an absolute URL # where there was none before parsed = ["", *parsed] new_path = "/".join(parsed) return URL( self._val._replace(path=new_path, query="", fragment=""), encoded=True )
(self, segments, encoded=False)
18,287
yarl._url
_query_var
null
@staticmethod def _query_var(v): cls = type(v) if issubclass(cls, str): return v if issubclass(cls, float): if math.isinf(v): raise ValueError("float('inf') is not supported") if math.isnan(v): raise ValueError("float('nan') is not supported") return str(float(v)) if issubclass(cls, int) and cls is not bool: return str(int(v)) raise TypeError( "Invalid variable type: value " "should be str, int or float, got {!r} " "of type {}".format(v, cls) )
(v)
18,288
yarl._url
_validate_authority_uri_abs_path
Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not.
@staticmethod def _validate_authority_uri_abs_path(host, path): """Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not. """ if len(host) > 0 and len(path) > 0 and not path.startswith("/"): raise ValueError( "Path in a URL with authority should start with a slash ('/') if set" )
(host, path)
18,289
yarl._url
human_repr
Return decoded human readable string for URL representation.
def human_repr(self): """Return decoded human readable string for URL representation.""" user = _human_quote(self.user, "#/:?@[]") password = _human_quote(self.password, "#/:?@[]") host = self.host if host: host = self._encode_host(self.host, human=True) path = _human_quote(self.path, "#?") query_string = "&".join( "{}={}".format(_human_quote(k, "#&+;="), _human_quote(v, "#&+;=")) for k, v in self.query.items() ) fragment = _human_quote(self.fragment, "") return urlunsplit( SplitResult( self.scheme, self._make_netloc( user, password, host, self._val.port, encode_host=False, ), path, query_string, fragment, ) )
(self)
18,290
yarl._url
is_absolute
A check for absolute URLs. Return True for absolute ones (having scheme or starting with //), False otherwise.
def is_absolute(self): """A check for absolute URLs. Return True for absolute ones (having scheme or starting with //), False otherwise. """ return self.raw_host is not None
(self)
18,291
yarl._url
is_default_port
A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise.
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self.scheme) if default is None: return False return self.port == default
(self)
18,292
yarl._url
join
Join URLs Construct a full (“absolute”) URL by combining a “base URL” (self) with another URL (url). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL.
def join(self, url): """Join URLs Construct a full (“absolute”) URL by combining a “base URL” (self) with another URL (url). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL. """ # See docs for urllib.parse.urljoin if not isinstance(url, URL): raise TypeError("url should be URL") return URL(urljoin(str(self), str(url)), encoded=True)
(self, url)
18,293
yarl._url
joinpath
Return a new URL with the elements in other appended to the path.
def joinpath(self, *other, encoded=False): """Return a new URL with the elements in other appended to the path.""" return self._make_child(other, encoded=encoded)
(self, *other, encoded=False)
18,294
yarl._url
origin
Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed.
def origin(self): """Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed. """ # TODO: add a keyword-only option for keeping user/pass maybe? if not self.is_absolute(): raise ValueError("URL should be absolute") if not self._val.scheme: raise ValueError("URL should have scheme") v = self._val netloc = self._make_netloc(None, None, v.hostname, v.port) val = v._replace(netloc=netloc, path="", query="", fragment="") return URL(val, encoded=True)
(self)
18,295
yarl._url
relative
Return a relative part of the URL. scheme, user, password, host and port are removed.
def relative(self): """Return a relative part of the URL. scheme, user, password, host and port are removed. """ if not self.is_absolute(): raise ValueError("URL should be absolute") val = self._val._replace(scheme="", netloc="") return URL(val, encoded=True)
(self)
18,296
yarl._url
update_query
Return a new URL with query part updated.
def update_query(self, *args, **kwargs): """Return a new URL with query part updated.""" s = self._get_str_query(*args, **kwargs) query = None if s is not None: new_query = MultiDict(parse_qsl(s, keep_blank_values=True)) query = MultiDict(self.query) query.update(new_query) return URL( self._val._replace(query=self._get_str_query(query) or ""), encoded=True )
(self, *args, **kwargs)
18,297
yarl._url
with_fragment
Return a new URL with fragment replaced. Autoencode fragment if needed. Clear fragment to default if None is passed.
def with_fragment(self, fragment): """Return a new URL with fragment replaced. Autoencode fragment if needed. Clear fragment to default if None is passed. """ # N.B. doesn't cleanup query/fragment if fragment is None: raw_fragment = "" elif not isinstance(fragment, str): raise TypeError("Invalid fragment type") else: raw_fragment = self._FRAGMENT_QUOTER(fragment) if self.raw_fragment == raw_fragment: return self return URL(self._val._replace(fragment=raw_fragment), encoded=True)
(self, fragment)
18,298
yarl._url
with_host
Return a new URL with host replaced. Autoencode host if needed. Changing host for relative URLs is not allowed, use .join() instead.
def with_host(self, host): """Return a new URL with host replaced. Autoencode host if needed. Changing host for relative URLs is not allowed, use .join() instead. """ # N.B. doesn't cleanup query/fragment if not isinstance(host, str): raise TypeError("Invalid host type") if not self.is_absolute(): raise ValueError("host replacement is not allowed for relative URLs") if not host: raise ValueError("host removing is not allowed") val = self._val return URL( self._val._replace( netloc=self._make_netloc(val.username, val.password, host, val.port) ), encoded=True, )
(self, host)
18,299
yarl._url
with_name
Return a new URL with name (last part of path) replaced. Query and fragment parts are cleaned up. Name is encoded if needed.
def with_name(self, name): """Return a new URL with name (last part of path) replaced. Query and fragment parts are cleaned up. Name is encoded if needed. """ # N.B. DOES cleanup query/fragment if not isinstance(name, str): raise TypeError("Invalid name type") if "/" in name: raise ValueError("Slash in name is not allowed") name = self._PATH_QUOTER(name) if name in (".", ".."): raise ValueError(". and .. values are forbidden") parts = list(self.raw_parts) if self.is_absolute(): if len(parts) == 1: parts.append(name) else: parts[-1] = name parts[0] = "" # replace leading '/' else: parts[-1] = name if parts[0] == "/": parts[0] = "" # replace leading '/' return URL( self._val._replace(path="/".join(parts), query="", fragment=""), encoded=True, )
(self, name)
18,300
yarl._url
with_password
Return a new URL with password replaced. Autoencode password if needed. Clear password if argument is None.
def with_password(self, password): """Return a new URL with password replaced. Autoencode password if needed. Clear password if argument is None. """ # N.B. doesn't cleanup query/fragment if password is None: pass elif isinstance(password, str): password = self._QUOTER(password) else: raise TypeError("Invalid password type") if not self.is_absolute(): raise ValueError("password replacement is not allowed for relative URLs") val = self._val return URL( self._val._replace( netloc=self._make_netloc(val.username, password, val.hostname, val.port) ), encoded=True, )
(self, password)
18,301
yarl._url
with_path
Return a new URL with path replaced.
def with_path(self, path, *, encoded=False): """Return a new URL with path replaced.""" if not encoded: path = self._PATH_QUOTER(path) if self.is_absolute(): path = self._normalize_path(path) if len(path) > 0 and path[0] != "/": path = "/" + path return URL(self._val._replace(path=path, query="", fragment=""), encoded=True)
(self, path, *, encoded=False)
18,302
yarl._url
with_port
Return a new URL with port replaced. Clear port to default if None is passed.
def with_port(self, port): """Return a new URL with port replaced. Clear port to default if None is passed. """ # N.B. doesn't cleanup query/fragment if port is not None: if isinstance(port, bool) or not isinstance(port, int): raise TypeError(f"port should be int or None, got {type(port)}") if port < 0 or port > 65535: raise ValueError(f"port must be between 0 and 65535, got {port}") if not self.is_absolute(): raise ValueError("port replacement is not allowed for relative URLs") val = self._val return URL( self._val._replace( netloc=self._make_netloc(val.username, val.password, val.hostname, port) ), encoded=True, )
(self, port)
18,303
yarl._url
with_query
Return a new URL with query part replaced. Accepts any Mapping (e.g. dict, multidict.MultiDict instances) or str, autoencode the argument if needed. A sequence of (key, value) pairs is supported as well. It also can take an arbitrary number of keyword arguments. Clear query if None is passed.
def with_query(self, *args, **kwargs): """Return a new URL with query part replaced. Accepts any Mapping (e.g. dict, multidict.MultiDict instances) or str, autoencode the argument if needed. A sequence of (key, value) pairs is supported as well. It also can take an arbitrary number of keyword arguments. Clear query if None is passed. """ # N.B. doesn't cleanup query/fragment new_query = self._get_str_query(*args, **kwargs) or "" return URL( self._val._replace(path=self._val.path, query=new_query), encoded=True )
(self, *args, **kwargs)
18,304
yarl._url
with_scheme
Return a new URL with scheme replaced.
def with_scheme(self, scheme): """Return a new URL with scheme replaced.""" # N.B. doesn't cleanup query/fragment if not isinstance(scheme, str): raise TypeError("Invalid scheme type") if not self.is_absolute(): raise ValueError("scheme replacement is not allowed for relative URLs") return URL(self._val._replace(scheme=scheme.lower()), encoded=True)
(self, scheme)
18,305
yarl._url
with_suffix
Return a new URL with suffix (file extension of name) replaced. Query and fragment parts are cleaned up. suffix is encoded if needed.
def with_suffix(self, suffix): """Return a new URL with suffix (file extension of name) replaced. Query and fragment parts are cleaned up. suffix is encoded if needed. """ if not isinstance(suffix, str): raise TypeError("Invalid suffix type") if suffix and not suffix.startswith(".") or suffix == ".": raise ValueError(f"Invalid suffix {suffix!r}") name = self.raw_name if not name: raise ValueError(f"{self!r} has an empty name") old_suffix = self.raw_suffix if not old_suffix: name = name + suffix else: name = name[: -len(old_suffix)] + suffix return self.with_name(name)
(self, suffix)
18,306
yarl._url
with_user
Return a new URL with user replaced. Autoencode user if needed. Clear user/password if user is None.
def with_user(self, user): """Return a new URL with user replaced. Autoencode user if needed. Clear user/password if user is None. """ # N.B. doesn't cleanup query/fragment val = self._val if user is None: password = None elif isinstance(user, str): user = self._QUOTER(user) password = val.password else: raise TypeError("Invalid user type") if not self.is_absolute(): raise ValueError("user replacement is not allowed for relative URLs") return URL( self._val._replace( netloc=self._make_netloc(user, password, val.hostname, val.port) ), encoded=True, )
(self, user)
18,317
plotly_football_pitch.pitch_background
AttackVsDefenceBackground
Colour each half of the pitch for a team, left=attack, right=defence.
class AttackVsDefenceBackground(PitchBackground): """Colour each half of the pitch for a team, left=attack, right=defence.""" def __init__(self, attack_colour: str, defence_colour: str): """Colour each half of the pitch per team, left=attack, right=defence. Args: attack_colour (str): Colour for the attacking team's half, the left side of the pitch. defence_colour (str): Colour for the defending team's half, the right side of the pitch. """ self.attack_colour = attack_colour self.defence_colour = defence_colour def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add attacking and defending team backgrounds to a pitch. Follows the standard convention for horizontal pitches whereby the left hand side represents the attacking team and the right hand side the defending team. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. Returns: plotly.graph_objects.Figure """ attack_half = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": 0, "x1": dimensions.pitch_mid_length_metres, } defence_half = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": dimensions.pitch_mid_length_metres, "x1": dimensions.pitch_length_metres, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( attack_half, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=self.attack_colour, fillcolor=self.attack_colour, layer="below", ) fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( defence_half, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=self.defence_colour, fillcolor=self.defence_colour, layer="below", ) return fig
(attack_colour: str, defence_colour: str)
18,318
plotly_football_pitch.pitch_background
__init__
Colour each half of the pitch per team, left=attack, right=defence. Args: attack_colour (str): Colour for the attacking team's half, the left side of the pitch. defence_colour (str): Colour for the defending team's half, the right side of the pitch.
def __init__(self, attack_colour: str, defence_colour: str): """Colour each half of the pitch per team, left=attack, right=defence. Args: attack_colour (str): Colour for the attacking team's half, the left side of the pitch. defence_colour (str): Colour for the defending team's half, the right side of the pitch. """ self.attack_colour = attack_colour self.defence_colour = defence_colour
(self, attack_colour: str, defence_colour: str)
18,319
typing
_proto_hook
null
def __init_subclass__(cls, *args, **kwargs): super().__init_subclass__(*args, **kwargs) # Determine if this is a protocol or a concrete subclass. if not cls.__dict__.get('_is_protocol', False): cls._is_protocol = any(b is Protocol for b in cls.__bases__) # Set (or override) the protocol subclass hook. def _proto_hook(other): if not cls.__dict__.get('_is_protocol', False): return NotImplemented # First, perform various sanity checks. if not getattr(cls, '_is_runtime_protocol', False): if _allow_reckless_class_checks(): return NotImplemented raise TypeError("Instance and class checks can only be used with" " @runtime_checkable protocols") if not _is_callable_members_only(cls): if _allow_reckless_class_checks(): return NotImplemented raise TypeError("Protocols with non-method members" " don't support issubclass()") if not isinstance(other, type): # Same error message as for issubclass(1, int). raise TypeError('issubclass() arg 1 must be a class') # Second, perform the actual structural compatibility check. for attr in _get_protocol_attrs(cls): for base in other.__mro__: # Check if the members appears in the class dictionary... if attr in base.__dict__: if base.__dict__[attr] is None: return NotImplemented break # ...or in annotations, if it is a sub-protocol. annotations = getattr(base, '__annotations__', {}) if (isinstance(annotations, collections.abc.Mapping) and attr in annotations and issubclass(other, Generic) and other._is_protocol): break else: return NotImplemented return True if '__subclasshook__' not in cls.__dict__: cls.__subclasshook__ = _proto_hook # We have nothing more to do for non-protocols... if not cls._is_protocol: return # ... otherwise check consistency of bases, and prohibit instantiation. for base in cls.__bases__: if not (base in (object, Generic) or base.__module__ in _PROTO_ALLOWLIST and base.__name__ in _PROTO_ALLOWLIST[base.__module__] or issubclass(base, Generic) and base._is_protocol): raise TypeError('Protocols can only inherit from other' ' protocols, got %r' % base) cls.__init__ = _no_init_or_replace_init
(other)
18,320
plotly_football_pitch.pitch_background
add_background
Add attacking and defending team backgrounds to a pitch. Follows the standard convention for horizontal pitches whereby the left hand side represents the attacking team and the right hand side the defending team. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. Returns: plotly.graph_objects.Figure
def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add attacking and defending team backgrounds to a pitch. Follows the standard convention for horizontal pitches whereby the left hand side represents the attacking team and the right hand side the defending team. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. Returns: plotly.graph_objects.Figure """ attack_half = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": 0, "x1": dimensions.pitch_mid_length_metres, } defence_half = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": dimensions.pitch_mid_length_metres, "x1": dimensions.pitch_length_metres, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( attack_half, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=self.attack_colour, fillcolor=self.attack_colour, layer="below", ) fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( defence_half, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=self.defence_colour, fillcolor=self.defence_colour, layer="below", ) return fig
(self, fig: plotly.graph_objs._figure.Figure, dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation) -> plotly.graph_objs._figure.Figure
18,321
plotly_football_pitch.pitch_background
ChequeredBackground
Chequered pitch using two alternating colours.
class ChequeredBackground(PitchBackground): """Chequered pitch using two alternating colours.""" def __init__( self, colours: List[str], num_horizontal_stripes: int = 10, num_vertical_stripes: int = 10, ): """Chequered pitch using two alternating colours. Args: colours (list[str]): A list of two colours to alternate for the chequered effect. num_horizontal_stripes (int): Number of horizontal stripes in the chequered effect (i.e. number of rows). num_vertical_stripes (int): Number of vertical stripes in the chequered effect (i.e. number of columns). Raises: ValueError: If `colours` does not have length 2. """ if len(colours) != 2: raise ValueError( f"{self.__class__.__name__} expects `colours` to have length 2" f", input was {colours}." ) self.colours = colours self.num_horizontal_stripes = num_horizontal_stripes self.num_vertical_stripes = num_vertical_stripes def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_height_metres = ( dimensions.pitch_width_metres / self.num_horizontal_stripes ) stripe_width_metres = dimensions.pitch_length_metres / self.num_vertical_stripes for row_index in range(self.num_horizontal_stripes): colour_cycle = itertools.cycle(self.colours) if row_index % 2 == 1: # alternate first colour per row next(colour_cycle) column_iterator = zip( range(self.num_vertical_stripes), colour_cycle, ) for column_index, colour in column_iterator: stripe = { "x0": column_index * stripe_width_metres, "y0": row_index * stripe_height_metres, } stripe["x1"] = stripe["x0"] + stripe_width_metres stripe["y1"] = stripe["y0"] + stripe_height_metres fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(colours: List[str], num_horizontal_stripes: int = 10, num_vertical_stripes: int = 10)
18,322
plotly_football_pitch.pitch_background
__init__
Chequered pitch using two alternating colours. Args: colours (list[str]): A list of two colours to alternate for the chequered effect. num_horizontal_stripes (int): Number of horizontal stripes in the chequered effect (i.e. number of rows). num_vertical_stripes (int): Number of vertical stripes in the chequered effect (i.e. number of columns). Raises: ValueError: If `colours` does not have length 2.
def __init__( self, colours: List[str], num_horizontal_stripes: int = 10, num_vertical_stripes: int = 10, ): """Chequered pitch using two alternating colours. Args: colours (list[str]): A list of two colours to alternate for the chequered effect. num_horizontal_stripes (int): Number of horizontal stripes in the chequered effect (i.e. number of rows). num_vertical_stripes (int): Number of vertical stripes in the chequered effect (i.e. number of columns). Raises: ValueError: If `colours` does not have length 2. """ if len(colours) != 2: raise ValueError( f"{self.__class__.__name__} expects `colours` to have length 2" f", input was {colours}." ) self.colours = colours self.num_horizontal_stripes = num_horizontal_stripes self.num_vertical_stripes = num_vertical_stripes
(self, colours: List[str], num_horizontal_stripes: int = 10, num_vertical_stripes: int = 10)
18,324
plotly_football_pitch.pitch_background
add_background
Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure
def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_height_metres = ( dimensions.pitch_width_metres / self.num_horizontal_stripes ) stripe_width_metres = dimensions.pitch_length_metres / self.num_vertical_stripes for row_index in range(self.num_horizontal_stripes): colour_cycle = itertools.cycle(self.colours) if row_index % 2 == 1: # alternate first colour per row next(colour_cycle) column_iterator = zip( range(self.num_vertical_stripes), colour_cycle, ) for column_index, colour in column_iterator: stripe = { "x0": column_index * stripe_width_metres, "y0": row_index * stripe_height_metres, } stripe["x1"] = stripe["x0"] + stripe_width_metres stripe["y1"] = stripe["y0"] + stripe_height_metres fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(self, fig: plotly.graph_objs._figure.Figure, dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation) -> plotly.graph_objs._figure.Figure
18,325
plotly_football_pitch.pitch_background
HorizontalStripesBackground
Horizontal stripes using specified colour cycle.
class HorizontalStripesBackground(PitchBackground): """Horizontal stripes using specified colour cycle.""" def __init__(self, colours: List[str], num_stripes: int = 10): """Horizontal stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of horizontal stripes to use, default 10. """ self.colours = colours self.num_stripes = num_stripes def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_metres = dimensions.pitch_width_metres / self.num_stripes colour_cycle = itertools.cycle(self.colours) for index, colour in zip(range(self.num_stripes), colour_cycle): y0 = index * stripe_metres y1 = y0 + stripe_metres stripe = { "y0": y0, "y1": y1, "x0": 0, "x1": dimensions.pitch_length_metres, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")], ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(colours: List[str], num_stripes: int = 10)
18,326
plotly_football_pitch.pitch_background
__init__
Horizontal stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of horizontal stripes to use, default 10.
def __init__(self, colours: List[str], num_stripes: int = 10): """Horizontal stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of horizontal stripes to use, default 10. """ self.colours = colours self.num_stripes = num_stripes
(self, colours: List[str], num_stripes: int = 10)
18,328
plotly_football_pitch.pitch_background
add_background
Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure
def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_metres = dimensions.pitch_width_metres / self.num_stripes colour_cycle = itertools.cycle(self.colours) for index, colour in zip(range(self.num_stripes), colour_cycle): y0 = index * stripe_metres y1 = y0 + stripe_metres stripe = { "y0": y0, "y1": y1, "x0": 0, "x1": dimensions.pitch_length_metres, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")], ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(self, fig: plotly.graph_objs._figure.Figure, dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation) -> plotly.graph_objs._figure.Figure
18,329
plotly_football_pitch.pitch_dimensions
PitchDimensions
Dimensions for a football pitch plot. All units are in metres. Length refers to the longer pitch dimension, which for a horizontal pitch will be the plot's x-axis. Width refers to the shorter pitch dimension, which for a horizontal pitch will be the plot's y-axis. The axes will be reversed for a vertical pitch. The origin is the bottom left hand corner of the pitch.
class PitchDimensions: """Dimensions for a football pitch plot. All units are in metres. Length refers to the longer pitch dimension, which for a horizontal pitch will be the plot's x-axis. Width refers to the shorter pitch dimension, which for a horizontal pitch will be the plot's y-axis. The axes will be reversed for a vertical pitch. The origin is the bottom left hand corner of the pitch. """ pitch_width_metres: int = 68 pitch_length_metres: int = 105 @property def pitch_mid_length_metres(self): """Distance of the centre line in metres from goal lines.""" return self.pitch_length_metres / 2 @property def pitch_mid_width_metres(self): """Distance in metres from side lines to the centre spot.""" return self.pitch_width_metres / 2 @property def penalty_box_length_metres(self): """Penalty box length in metres (18 yards in metres).""" return 18 / 1.09361 @property def penalty_box_width_metres(self): """Width of the penalty box in metres.""" return self.pitch_width_metres * 0.6 @property def penalty_box_width_max_metres(self): """Metres from the bottom touchline to top of penalty box.""" outside_box_metres = self.pitch_width_metres - self.penalty_box_width_metres return self.pitch_width_metres - outside_box_metres / 2 @property def penalty_box_width_min_metres(self): """Metres from the bottom touchline to bottom of penalty box.""" outside_box_metres = self.pitch_width_metres - self.penalty_box_width_metres return outside_box_metres / 2 @property def six_yard_box_length_metres(self): """Six yard box length in metres (6 yards in metres).""" return self.penalty_box_length_metres / 3 @property def six_yard_box_width_metres(self): """Width of the six yard box in metres.""" return self.pitch_width_metres * 0.3 @property def six_yard_box_width_max_metres(self): """Metres from the bottom touchline to top of six yard box.""" outside_box_metres = self.pitch_width_metres - self.six_yard_box_width_metres return self.pitch_width_metres - outside_box_metres / 2 @property def six_yard_box_width_min_metres(self): """Metres from the bottom touchline to bottom of six yard box.""" outside_box_metres = self.pitch_width_metres - self.six_yard_box_width_metres return outside_box_metres / 2 @property def penalty_spot_length_metres(self): """Penalty spot distance from goal line (12 yards in metres).""" return 2 * self.penalty_box_length_metres / 3 @property def centre_circle_radius_metres(self): """Radius of the centre circle in metres.""" return self.pitch_length_metres / 10
(pitch_width_metres: int = 68, pitch_length_metres: int = 105) -> None
18,330
plotly_football_pitch.pitch_dimensions
__eq__
null
"""Configuration for the dimensions/orientation of a football pitch to plot.""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Tuple @dataclass class PitchDimensions: """Dimensions for a football pitch plot. All units are in metres. Length refers to the longer pitch dimension, which for a horizontal pitch will be the plot's x-axis. Width refers to the shorter pitch dimension, which for a horizontal pitch will be the plot's y-axis. The axes will be reversed for a vertical pitch. The origin is the bottom left hand corner of the pitch. """ pitch_width_metres: int = 68 pitch_length_metres: int = 105 @property def pitch_mid_length_metres(self): """Distance of the centre line in metres from goal lines.""" return self.pitch_length_metres / 2 @property def pitch_mid_width_metres(self): """Distance in metres from side lines to the centre spot.""" return self.pitch_width_metres / 2 @property def penalty_box_length_metres(self): """Penalty box length in metres (18 yards in metres).""" return 18 / 1.09361 @property def penalty_box_width_metres(self): """Width of the penalty box in metres.""" return self.pitch_width_metres * 0.6 @property def penalty_box_width_max_metres(self): """Metres from the bottom touchline to top of penalty box.""" outside_box_metres = self.pitch_width_metres - self.penalty_box_width_metres return self.pitch_width_metres - outside_box_metres / 2 @property def penalty_box_width_min_metres(self): """Metres from the bottom touchline to bottom of penalty box.""" outside_box_metres = self.pitch_width_metres - self.penalty_box_width_metres return outside_box_metres / 2 @property def six_yard_box_length_metres(self): """Six yard box length in metres (6 yards in metres).""" return self.penalty_box_length_metres / 3 @property def six_yard_box_width_metres(self): """Width of the six yard box in metres.""" return self.pitch_width_metres * 0.3 @property def six_yard_box_width_max_metres(self): """Metres from the bottom touchline to top of six yard box.""" outside_box_metres = self.pitch_width_metres - self.six_yard_box_width_metres return self.pitch_width_metres - outside_box_metres / 2 @property def six_yard_box_width_min_metres(self): """Metres from the bottom touchline to bottom of six yard box.""" outside_box_metres = self.pitch_width_metres - self.six_yard_box_width_metres return outside_box_metres / 2 @property def penalty_spot_length_metres(self): """Penalty spot distance from goal line (12 yards in metres).""" return 2 * self.penalty_box_length_metres / 3 @property def centre_circle_radius_metres(self): """Radius of the centre circle in metres.""" return self.pitch_length_metres / 10
(self, other)
18,333
plotly_football_pitch.pitch_dimensions
PitchOrientation
Orientation of a pitch. Horizontal means that the plot's x-axis will represent the longer dimension of the pitch, and the plot's y-axis will represent the shorter dimension of the pitch. The axes are reversed for a vertically oriented pitch.
class PitchOrientation(Enum): """Orientation of a pitch. Horizontal means that the plot's x-axis will represent the longer dimension of the pitch, and the plot's y-axis will represent the shorter dimension of the pitch. The axes are reversed for a vertically oriented pitch. """ HORIZONTAL = 0 VERTICAL = 1 def switch_axes_if_required( self, coordinate_data: dict, keys_to_switch: Optional[List[Tuple[str, str]]] = None, ) -> dict: """Switch axes of data for vertically oriented pitches. Args: coordinate_data (dict): Data to show on the plot. Keys will refer to plot axes e.g. 'x', 'y', 'x0' or 'y1'. keys_to_switch (Optional[list[tuple[str, str]]]): Pairs for keys in `coordinate_data` to swap for a vertically oriented pitch. Defaults to [('x', 'y')], which will work for plotting lines and scatter points. Only keys present in some tuple will be included in the output, therefore no additional key-value pairs should be included in `coordinate_data`. Returns: dict: Dictionary with coordinate data whose axes have been switched for a vertically oriented pitch. """ if keys_to_switch is None: keys_to_switch = [("x", "y")] if self == PitchOrientation.HORIZONTAL: return coordinate_data else: switched_coordinate_data = {} for key_1, key_2 in keys_to_switch: switched_coordinate_data[key_1] = coordinate_data[key_2] switched_coordinate_data[key_2] = coordinate_data[key_1] return switched_coordinate_data
(value, names=None, *, module=None, qualname=None, type=None, start=1)
18,334
plotly_football_pitch.pitch_background
SingleColourBackground
Add a single colour background to a fooball pitch.
class SingleColourBackground(PitchBackground): """Add a single colour background to a fooball pitch.""" def __init__(self, colour: str): """Add a single colour background to a fooball pitch. Args: colour (str): Colour for the background. """ self.colour = colour def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add a single-coloured background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ if orientation == PitchOrientation.HORIZONTAL: rect_method = fig.add_hrect coordinates_data = { "y0": 0, "y1": dimensions.pitch_width_metres, } else: rect_method = fig.add_vrect coordinates_data = { "x0": 0, "x1": dimensions.pitch_width_metres, } return rect_method( **coordinates_data, fillcolor=self.colour, layer="below", )
(colour: str)
18,335
plotly_football_pitch.pitch_background
__init__
Add a single colour background to a fooball pitch. Args: colour (str): Colour for the background.
def __init__(self, colour: str): """Add a single colour background to a fooball pitch. Args: colour (str): Colour for the background. """ self.colour = colour
(self, colour: str)
18,337
plotly_football_pitch.pitch_background
add_background
Add a single-coloured background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure
def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation ) -> go.Figure: """Add a single-coloured background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ if orientation == PitchOrientation.HORIZONTAL: rect_method = fig.add_hrect coordinates_data = { "y0": 0, "y1": dimensions.pitch_width_metres, } else: rect_method = fig.add_vrect coordinates_data = { "x0": 0, "x1": dimensions.pitch_width_metres, } return rect_method( **coordinates_data, fillcolor=self.colour, layer="below", )
(self, fig: plotly.graph_objs._figure.Figure, dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation) -> plotly.graph_objs._figure.Figure
18,338
plotly_football_pitch.pitch_background
VerticalStripesBackground
Vertical stripes using specified colour cycle.
class VerticalStripesBackground(PitchBackground): """Vertical stripes using specified colour cycle.""" def __init__(self, colours: List[str], num_stripes: int = 10): """Vertical stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of vertical stripes to use, default 10. """ self.colours = colours self.num_stripes = num_stripes def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation, ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_metres = dimensions.pitch_length_metres / self.num_stripes colour_cycle = itertools.cycle(self.colours) for index, colour in zip(range(self.num_stripes), colour_cycle): x0 = index * stripe_metres x1 = x0 + stripe_metres stripe = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": x0, "x1": x1, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")], ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(colours: List[str], num_stripes: int = 10)
18,339
plotly_football_pitch.pitch_background
__init__
Vertical stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of vertical stripes to use, default 10.
def __init__(self, colours: List[str], num_stripes: int = 10): """Vertical stripes using specified colour cycle. Args: colours (list[str]): A list of colours to cycle through for the stripes. num_stripes (int): Number of vertical stripes to use, default 10. """ self.colours = colours self.num_stripes = num_stripes
(self, colours: List[str], num_stripes: int = 10)
18,341
plotly_football_pitch.pitch_background
add_background
Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure
def add_background( self, fig: go.Figure, dimensions: PitchDimensions, orientation: PitchOrientation, ) -> go.Figure: """Add vertically-striped background to a pitch. Args: fig (plotly.graph_objects.Figure): Figure with pitch markings already drawn. dimensions (PitchDimensions): Dimensions of the pitch. orientation (PitchOrientation): Orientation of the pitch. Returns: plotly.graph_objects.Figure """ stripe_metres = dimensions.pitch_length_metres / self.num_stripes colour_cycle = itertools.cycle(self.colours) for index, colour in zip(range(self.num_stripes), colour_cycle): x0 = index * stripe_metres x1 = x0 + stripe_metres stripe = { "y0": 0, "y1": dimensions.pitch_width_metres, "x0": x0, "x1": x1, } fig = fig.add_shape( type="rect", **orientation.switch_axes_if_required( stripe, keys_to_switch=[("x0", "y0"), ("x1", "y1")], ), line_color=colour, fillcolor=colour, layer="below", ) return fig
(self, fig: plotly.graph_objs._figure.Figure, dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation) -> plotly.graph_objs._figure.Figure
18,342
plotly_football_pitch.pitch_plot
add_heatmap
Add a heatmap to an existing figure. Args: fig (plotly.graph_objects.Figure): Figure on which to add heatmap. Expected to have axis ranges directly set so that `fig.layout.xaxis.range` and `fig.layout.yaxis.range` are not None. data (np.ndarray): 2-dimensional arrays of values to plot on the figure. Number of grid squares in each dimension will be inferred from the shape of this array. The i'th row of the array corresponds to the i'th row of the grid on the pitch starting from the bottom, while the j'th column of the array corresponds to the j'th column of the grid starting from the left hand side. Thus, in particular, `data[0, 0]` corresponds to the bottom left grid square. Returns: plotly.graph_objects.Figure
def add_heatmap(fig: go.Figure, data: np.ndarray, **kwargs) -> go.Figure: """Add a heatmap to an existing figure. Args: fig (plotly.graph_objects.Figure): Figure on which to add heatmap. Expected to have axis ranges directly set so that `fig.layout.xaxis.range` and `fig.layout.yaxis.range` are not None. data (np.ndarray): 2-dimensional arrays of values to plot on the figure. Number of grid squares in each dimension will be inferred from the shape of this array. The i'th row of the array corresponds to the i'th row of the grid on the pitch starting from the bottom, while the j'th column of the array corresponds to the j'th column of the grid starting from the left hand side. Thus, in particular, `data[0, 0]` corresponds to the bottom left grid square. Returns: plotly.graph_objects.Figure """ if "colorscale" not in kwargs: kwargs["colorscale"] = px.colors.sequential.Reds if "hovertemplate" not in kwargs: kwargs["hovertemplate"] = "%{z}<extra></extra>" _, plot_width = fig.layout.xaxis.range _, plot_height = fig.layout.yaxis.range dx = plot_width / data.shape[1] dy = plot_height / data.shape[0] heatmap = go.Heatmap(z=data, dx=dx, dy=dy, y0=dy / 2, x0=dx / 2, **kwargs) fig.add_trace(heatmap) return fig
(fig: plotly.graph_objs._figure.Figure, data: numpy.ndarray, **kwargs) -> plotly.graph_objs._figure.Figure
18,343
plotly_football_pitch.pitch_plot
make_pitch_figure
Create a plotly figure of a football pitch with markings. Some markings which appear in both team's halves e.g. penalty box arc, are defined in terms of the attacking team and the defending team. For a horizontally oriented pitch the attacking team's half is the left hand one, while for a vertically oriented one their half is the bottom one. Args: dimensions (PitchDimensions): Dimensions of the pitch to plot. marking_colour (str): Colour of the pitch markings, default "black". marking_width (int): Width of the pitch markings, default 4. pitch_background (Optional[PitchBackground]): Strategy for plotting a background colour to the pitch. The default of None results in a transparent background. figure_width_pixels (int): Width of the figure, default 800. This corresponds to the long axis of the pitch (pitch length). figure_height_pixels (int): Height of the figure, default 600. This corresponds to the short axis of the pitch (pitch width). orientation (PitchOrientation): Orientation of the pitch, defaults to a horizontal pitch. Returns: plotly.graph_objects.Figure
def make_pitch_figure( dimensions: PitchDimensions, marking_colour: str = "black", marking_width: int = 4, pitch_background: Optional[PitchBackground] = None, figure_width_pixels: int = 800, figure_height_pixels: int = 600, orientation: PitchOrientation = PitchOrientation.HORIZONTAL, ) -> go.Figure: """Create a plotly figure of a football pitch with markings. Some markings which appear in both team's halves e.g. penalty box arc, are defined in terms of the attacking team and the defending team. For a horizontally oriented pitch the attacking team's half is the left hand one, while for a vertically oriented one their half is the bottom one. Args: dimensions (PitchDimensions): Dimensions of the pitch to plot. marking_colour (str): Colour of the pitch markings, default "black". marking_width (int): Width of the pitch markings, default 4. pitch_background (Optional[PitchBackground]): Strategy for plotting a background colour to the pitch. The default of None results in a transparent background. figure_width_pixels (int): Width of the figure, default 800. This corresponds to the long axis of the pitch (pitch length). figure_height_pixels (int): Height of the figure, default 600. This corresponds to the short axis of the pitch (pitch width). orientation (PitchOrientation): Orientation of the pitch, defaults to a horizontal pitch. Returns: plotly.graph_objects.Figure """ pitch_marking_style = { "mode": "lines", "line": {"color": marking_colour, "width": marking_width}, "hoverinfo": "skip", "showlegend": False, } spot_style = { "mode": "markers", "line": {"color": marking_colour}, "hoverinfo": "skip", "showlegend": False, } touchline = { "x": [0, dimensions.pitch_length_metres, dimensions.pitch_length_metres, 0, 0], "y": [0, 0, dimensions.pitch_width_metres, dimensions.pitch_width_metres, 0], } halfway_line = { "x": [dimensions.pitch_mid_length_metres, dimensions.pitch_mid_length_metres], "y": [0, dimensions.pitch_width_metres], } # attacking team's half is left for horizontal pitches (bottom for # vertical after rotation) penalty_boxes = { "attacking_team": { "x": [ 0, dimensions.penalty_box_length_metres, dimensions.penalty_box_length_metres, 0, ], "y": [ dimensions.penalty_box_width_min_metres, dimensions.penalty_box_width_min_metres, dimensions.penalty_box_width_max_metres, dimensions.penalty_box_width_max_metres, ], }, "defending_team": { "x": [ dimensions.pitch_length_metres, dimensions.pitch_length_metres - dimensions.penalty_box_length_metres, dimensions.pitch_length_metres - dimensions.penalty_box_length_metres, dimensions.pitch_length_metres, ], "y": [ dimensions.penalty_box_width_min_metres, dimensions.penalty_box_width_min_metres, dimensions.penalty_box_width_max_metres, dimensions.penalty_box_width_max_metres, ], }, } six_yard_boxes = { "attacking_team": { "x": [ 0, dimensions.six_yard_box_length_metres, dimensions.six_yard_box_length_metres, 0, ], "y": [ dimensions.six_yard_box_width_min_metres, dimensions.six_yard_box_width_min_metres, dimensions.six_yard_box_width_max_metres, dimensions.six_yard_box_width_max_metres, ], }, "defending_team": { "x": [ dimensions.pitch_length_metres, dimensions.pitch_length_metres - dimensions.six_yard_box_length_metres, dimensions.pitch_length_metres - dimensions.six_yard_box_length_metres, dimensions.pitch_length_metres, ], "y": [ dimensions.six_yard_box_width_min_metres, dimensions.six_yard_box_width_min_metres, dimensions.six_yard_box_width_max_metres, dimensions.six_yard_box_width_max_metres, ], }, } penalty_spots = { "attacking_team": { "x": [dimensions.penalty_spot_length_metres], "y": [dimensions.pitch_mid_width_metres], }, "defending_team": { "x": [ dimensions.pitch_length_metres - dimensions.penalty_spot_length_metres ], "y": [dimensions.pitch_mid_width_metres], }, } centre_spot = { "x": [dimensions.pitch_mid_length_metres], "y": [dimensions.pitch_mid_width_metres], } pitch_marking_coordinates_with_style = [ (touchline, pitch_marking_style), (halfway_line, pitch_marking_style), (penalty_boxes["attacking_team"], pitch_marking_style), (penalty_boxes["defending_team"], pitch_marking_style), (six_yard_boxes["attacking_team"], pitch_marking_style), (six_yard_boxes["defending_team"], pitch_marking_style), (penalty_spots["attacking_team"], spot_style), (penalty_spots["defending_team"], spot_style), (centre_spot, spot_style), ] pitch_markings = [ go.Scatter( **orientation.switch_axes_if_required(marking_coordinates), **style, ) for marking_coordinates, style in pitch_marking_coordinates_with_style ] fig = make_subplots() for markings in pitch_markings: fig.add_trace(markings) centre_circle = { "x0": dimensions.pitch_mid_length_metres + dimensions.centre_circle_radius_metres, "y0": dimensions.pitch_mid_width_metres + dimensions.centre_circle_radius_metres, "x1": dimensions.pitch_mid_length_metres - dimensions.centre_circle_radius_metres, "y1": dimensions.pitch_mid_width_metres - dimensions.centre_circle_radius_metres, } fig.add_shape( type="circle", xref="x", yref="y", line=pitch_marking_style["line"], name=None, **orientation.switch_axes_if_required( centre_circle, keys_to_switch=[("x0", "y0"), ("x1", "y1")] ), ) penalty_box_arcs = { "attacking_team": { "x_centre": dimensions.penalty_spot_length_metres, "y_centre": dimensions.pitch_mid_width_metres, }, "defending_team": { "x_centre": dimensions.pitch_length_metres - dimensions.penalty_spot_length_metres, "y_centre": dimensions.pitch_mid_width_metres, }, } start_angle = { "attacking_team": { PitchOrientation.HORIZONTAL: -np.pi / 3, PitchOrientation.VERTICAL: np.pi / 6, }, "defending_team": { PitchOrientation.HORIZONTAL: 2 * np.pi / 3, PitchOrientation.VERTICAL: -5 * np.pi / 6, }, } end_angle = { "attacking_team": { PitchOrientation.HORIZONTAL: np.pi / 3, PitchOrientation.VERTICAL: 5 * np.pi / 6, }, "defending_team": { PitchOrientation.HORIZONTAL: 4 * np.pi / 3, PitchOrientation.VERTICAL: -np.pi / 6, }, } path = make_ellipse_arc_svg_path( **orientation.switch_axes_if_required( penalty_box_arcs["attacking_team"], keys_to_switch=[("x_centre", "y_centre")], ), start_angle=start_angle["attacking_team"][orientation], end_angle=end_angle["attacking_team"][orientation], a=dimensions.penalty_spot_length_metres, b=dimensions.penalty_spot_length_metres, num_points=60, ) fig.add_shape( type="path", path=path, line=pitch_marking_style["line"], name=None, ) path = make_ellipse_arc_svg_path( **orientation.switch_axes_if_required( penalty_box_arcs["defending_team"], keys_to_switch=[("x_centre", "y_centre")], ), start_angle=start_angle["defending_team"][orientation], end_angle=end_angle["defending_team"][orientation], a=dimensions.penalty_spot_length_metres, b=dimensions.penalty_spot_length_metres, num_points=60, ) fig.add_shape( type="path", path=path, line=pitch_marking_style["line"], name=None, ) if pitch_background is not None: fig = pitch_background.add_background(fig, dimensions, orientation) axes_ranges = { "xaxis_range": [0, dimensions.pitch_length_metres], "yaxis_range": [0, dimensions.pitch_width_metres], } fig.update_layout( height=figure_height_pixels, width=figure_width_pixels, **orientation.switch_axes_if_required( axes_ranges, keys_to_switch=[("xaxis_range", "yaxis_range")] ), ) fig.update_xaxes(visible=False) fig.update_yaxes(visible=False) return fig
(dimensions: plotly_football_pitch.pitch_dimensions.PitchDimensions, marking_colour: str = 'black', marking_width: int = 4, pitch_background: Optional[plotly_football_pitch.pitch_background.PitchBackground] = None, figure_width_pixels: int = 800, figure_height_pixels: int = 600, orientation: plotly_football_pitch.pitch_dimensions.PitchOrientation = <PitchOrientation.HORIZONTAL: 0>) -> plotly.graph_objs._figure.Figure
18,347
jonf
_format_item
Formats Python nested item to JONF marker, space, text Args: item: Any data that can be converted to JSON is_unquoted_string: If we already found that `_is_unquoted_string(item) is True` Returns: marker: Either "-" or "=" space: Either " " or " " text: JONF text, representing this item
def _format_item(item: Any, is_unquoted_string: bool = False) -> Tuple[str, str, str]: """ Formats Python nested item to JONF marker, space, text Args: item: Any data that can be converted to JSON is_unquoted_string: If we already found that `_is_unquoted_string(item) is True` Returns: marker: Either "-" or "=" space: Either " " or "\n" text: JONF text, representing this item """ if is_unquoted_string or _is_unquoted_string(item): marker = "-" text = item else: marker = "=" text = format(item) lines = text.splitlines() assert lines if len(lines) == 1 and (not isinstance(item, COLLECTIONS) or item in EMPTIES): space = " " else: space = "\n" text = "\n".join(((INDENT + line) if line else "") for line in lines) return marker, space, text
(item: Any, is_unquoted_string: bool = False) -> Tuple[str, str, str]
18,348
jonf
_has_comment
Finds if this string data should be formatted as a quoted JSON string, because otherwise a part of this data will become a JONF comment
def _has_comment(data: str) -> bool: """ Finds if this string data should be formatted as a quoted JSON string, because otherwise a part of this data will become a JONF comment """ return data.startswith("#") or any(mark in data for mark in INNER_COMMENT_MARKS) # TODO: Compare performance with regex
(data: str) -> bool
18,349
jonf
_is_unquoted_string
Finds if this data should be represented as a JONF unquoted string
def _is_unquoted_string(data: Any) -> bool: """ Finds if this data should be represented as a JONF unquoted string """ return bool( isinstance(data, str) and data and data.strip() == data and not _has_comment(data) )
(data: Any) -> bool
18,350
jonf
format
Formats Python data to JONF text Args: data: Any data that can be converted to JSON json_format: JSON formatter to use, default is `json.dumps` Returns: JONF text, representing this data Example:: text = textwrap.dedent( ''' compare = - true = true ''' ).rstrip() assert jonf.format({"compare": ["true", True]}) == text
def format(data: Any, json_format: Callable[[Any], str] = json.dumps) -> str: """Formats Python data to JONF text Args: data: Any data that can be converted to JSON json_format: JSON formatter to use, default is `json.dumps` Returns: JONF text, representing this data Example:: text = textwrap.dedent( '''\ compare = - true = true ''' ).rstrip() assert jonf.format({"compare": ["true", True]}) == text """ if _is_unquoted_string(data): _, space, text = _format_item(data, is_unquoted_string=True) if space == "\n": return text if data is None or isinstance(data, BASIC_TYPES) or data in EMPTIES: return json_format(data) if isinstance(data, ARRAYS): return "\n".join("".join(_format_item(item)) for item in data) if isinstance(data, OBJECTS): chunks = [] for key, value in data.items(): if not isinstance(key, str): raise TypeError(f"Object key should be string, found: {repr(key)}") if any( mark in key for mark in OBJECT_KEY_MARKS_TO_QUOTE ) or not _is_unquoted_string(key): key = json_format(key) marker, space, value = _format_item(value) chunks.append(f"{key} {marker}{space}{value}") return "\n".join(chunks) # This will probably raise `TypeError: Object of type ... is not JSON serializable` # unless custom JSON formatter knows how to serialize it return json_format(data)
(data: Any, json_format: Callable[[Any], str] = <function dumps at 0x7fbc970c0b80>) -> str
18,352
jonf
parse
Parses JONF text to Python data Args: text: JONF text json_parse: JSON parser to use, default is `json.loads` Returns: Python data, parsed from this text Example:: text = textwrap.dedent( ''' compare = - true = true ''' ).rstrip() assert jonf.parse(text) == {"compare": ["true", True]}
def parse(text: str, json_parse: Callable[[str], Any] = json.loads) -> Any: """Parses JONF text to Python data Args: text: JONF text json_parse: JSON parser to use, default is `json.loads` Returns: Python data, parsed from this text Example:: text = textwrap.dedent( '''\ compare = - true = true ''' ).rstrip() assert jonf.parse(text) == {"compare": ["true", True]} """ raise NotImplementedError
(text: str, json_parse: Callable[[str], Any] = <function loads at 0x7fbc970c1120>) -> Any
18,353
qt5_applications
_application_names
null
def _application_names(): return [*qt_applications._applications.application_paths.keys()]
()
18,354
qt5_applications
_application_path
null
def _application_path(name): return _bin.joinpath(qt_applications._applications.application_paths[name])
(name)
18,357
qt5_applications
import_it
null
def import_it(*segments): import importlib import pkg_resources major = int(pkg_resources.get_distribution(__name__).version.partition(".")[0]) m = { "pyqt_tools": "pyqt{major}_tools".format(major=major), "pyqt_plugins": "pyqt{major}_plugins".format(major=major), "qt_tools": "qt{major}_tools".format(major=major), "qt_applications": "qt{major}_applications".format(major=major), } majored = [m[segments[0]], *segments[1:]] return importlib.import_module(".".join(majored))
(*segments)
18,360
envparse
ConfigurationError
null
class ConfigurationError(Exception): pass
null
18,361
envparse
Env
Lookup and cast environment variables with optional schema. Usage::: env = Env() env('foo') env.bool('bar') # Create env with a schema env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=(str, 'DEFAULT')) if env('MAIL_ENABLED'): ...
class Env(object): """ Lookup and cast environment variables with optional schema. Usage::: env = Env() env('foo') env.bool('bar') # Create env with a schema env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=(str, 'DEFAULT')) if env('MAIL_ENABLED'): ... """ BOOLEAN_TRUE_STRINGS = ('true', 'on', 'ok', 'y', 'yes', '1') def __init__(self, **schema): self.schema = schema def __call__(self, var, default=NOTSET, cast=None, subcast=None, force=False, preprocessor=None, postprocessor=None): """ Return value for given environment variable. :param var: Name of variable. :param default: If var not present in environ, return this instead. :param cast: Type or callable to cast return value as. :param subcast: Subtype or callable to cast return values as (used for nested structures). :param force: force to cast to type even if default is set. :param preprocessor: callable to run on pre-casted value. :param postprocessor: callable to run on casted value. :returns: Value from environment or default (if set). """ logger.debug("Get '%s' casted as '%s'/'%s' with default '%s'", var, cast, subcast, default) if var in self.schema: params = self.schema[var] if isinstance(params, dict): if cast is None: cast = params.get('cast', cast) if subcast is None: subcast = params.get('subcast', subcast) if default == NOTSET: default = params.get('default', default) else: if cast is None: cast = params # Default cast is `str` if it is not specified. Most types will be # implicitly strings so reduces having to specify. cast = str if cast is None else cast try: value = os.environ[var] except KeyError: if default is NOTSET: error_msg = "Environment variable '{}' not set.".format(var) raise ConfigurationError(error_msg) else: value = default # Resolve any proxied values if hasattr(value, 'startswith') and value.startswith('{{'): value = self.__call__(value.lstrip('{{}}'), default, cast, subcast, default, force, preprocessor, postprocessor) if preprocessor: value = preprocessor(value) if value != default or force: value = self.cast(value, cast, subcast) if postprocessor: value = postprocessor(value) return value @classmethod def cast(cls, value, cast=str, subcast=None): """ Parse and cast provided value. :param value: Stringed value. :param cast: Type or callable to cast return value as. :param subcast: Subtype or callable to cast return values as (used for nested structures). :returns: Value of type `cast`. """ if cast is bool: value = value.lower() in cls.BOOLEAN_TRUE_STRINGS elif cast is float: # Clean string float_str = re.sub(r'[^\d,\.]', '', value) # Split to handle thousand separator for different locales, i.e. # comma or dot being the placeholder. parts = re.split(r'[,\.]', float_str) if len(parts) == 1: float_str = parts[0] else: float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1]) value = float(float_str) elif type(cast) is type and (issubclass(cast, list) or issubclass(cast, tuple)): value = (subcast(i.strip()) if subcast else i.strip() for i in value.split(',') if i) elif cast is dict: value = {k.strip(): subcast(v.strip()) if subcast else v.strip() for k, v in (i.split('=') for i in value.split(',') if value)} try: return cast(value) except ValueError as error: raise ConfigurationError(*error.args) # Shortcuts bool = shortcut(bool) dict = shortcut(dict) float = shortcut(float) int = shortcut(int) list = shortcut(list) set = shortcut(set) str = shortcut(str) tuple = shortcut(tuple) json = shortcut(pyjson.loads) url = shortcut(urlparse.urlparse) @staticmethod def read_envfile(path=None, **overrides): """ Read a .env file (line delimited KEY=VALUE) into os.environ. If not given a path to the file, recurses up the directory tree until found. Uses code from Honcho (github.com/nickstenning/honcho) for parsing the file. """ if path is None: frame = inspect.currentframe().f_back caller_dir = os.path.dirname(frame.f_code.co_filename) path = os.path.join(os.path.abspath(caller_dir), '.env') try: with open(path, 'r') as f: content = f.read() except getattr(__builtins__, 'FileNotFoundError', IOError): logger.debug('envfile not found at %s, looking in parent dir.', path) filedir, filename = os.path.split(path) pardir = os.path.abspath(os.path.join(filedir, os.pardir)) path = os.path.join(pardir, filename) if filedir != pardir: Env.read_envfile(path, **overrides) else: # Reached top level directory. warnings.warn('Could not any envfile.') return logger.debug('Reading environment variables from: %s', path) for line in content.splitlines(): tokens = list(shlex.shlex(line, posix=True)) # parses the assignment statement if len(tokens) < 3: continue name, op = tokens[:2] value = ''.join(tokens[2:]) if op != '=': continue if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name): continue value = value.replace(r'\n', '\n').replace(r'\t', '\t') os.environ.setdefault(name, value) for name, value in overrides.items(): os.environ.setdefault(name, value)
(**schema)
18,362
envparse
__call__
Return value for given environment variable. :param var: Name of variable. :param default: If var not present in environ, return this instead. :param cast: Type or callable to cast return value as. :param subcast: Subtype or callable to cast return values as (used for nested structures). :param force: force to cast to type even if default is set. :param preprocessor: callable to run on pre-casted value. :param postprocessor: callable to run on casted value. :returns: Value from environment or default (if set).
def __call__(self, var, default=NOTSET, cast=None, subcast=None, force=False, preprocessor=None, postprocessor=None): """ Return value for given environment variable. :param var: Name of variable. :param default: If var not present in environ, return this instead. :param cast: Type or callable to cast return value as. :param subcast: Subtype or callable to cast return values as (used for nested structures). :param force: force to cast to type even if default is set. :param preprocessor: callable to run on pre-casted value. :param postprocessor: callable to run on casted value. :returns: Value from environment or default (if set). """ logger.debug("Get '%s' casted as '%s'/'%s' with default '%s'", var, cast, subcast, default) if var in self.schema: params = self.schema[var] if isinstance(params, dict): if cast is None: cast = params.get('cast', cast) if subcast is None: subcast = params.get('subcast', subcast) if default == NOTSET: default = params.get('default', default) else: if cast is None: cast = params # Default cast is `str` if it is not specified. Most types will be # implicitly strings so reduces having to specify. cast = str if cast is None else cast try: value = os.environ[var] except KeyError: if default is NOTSET: error_msg = "Environment variable '{}' not set.".format(var) raise ConfigurationError(error_msg) else: value = default # Resolve any proxied values if hasattr(value, 'startswith') and value.startswith('{{'): value = self.__call__(value.lstrip('{{}}'), default, cast, subcast, default, force, preprocessor, postprocessor) if preprocessor: value = preprocessor(value) if value != default or force: value = self.cast(value, cast, subcast) if postprocessor: value = postprocessor(value) return value
(self, var, default=<class 'envparse.NoValue'>, cast=None, subcast=None, force=False, preprocessor=None, postprocessor=None)
18,363
envparse
__init__
null
def __init__(self, **schema): self.schema = schema
(self, **schema)
18,364
envparse
method
null
def shortcut(cast): def method(self, var, **kwargs): return self.__call__(var, cast=cast, **kwargs) return method
(self, var, **kwargs)
18,370
envparse
read_envfile
Read a .env file (line delimited KEY=VALUE) into os.environ. If not given a path to the file, recurses up the directory tree until found. Uses code from Honcho (github.com/nickstenning/honcho) for parsing the file.
@staticmethod def read_envfile(path=None, **overrides): """ Read a .env file (line delimited KEY=VALUE) into os.environ. If not given a path to the file, recurses up the directory tree until found. Uses code from Honcho (github.com/nickstenning/honcho) for parsing the file. """ if path is None: frame = inspect.currentframe().f_back caller_dir = os.path.dirname(frame.f_code.co_filename) path = os.path.join(os.path.abspath(caller_dir), '.env') try: with open(path, 'r') as f: content = f.read() except getattr(__builtins__, 'FileNotFoundError', IOError): logger.debug('envfile not found at %s, looking in parent dir.', path) filedir, filename = os.path.split(path) pardir = os.path.abspath(os.path.join(filedir, os.pardir)) path = os.path.join(pardir, filename) if filedir != pardir: Env.read_envfile(path, **overrides) else: # Reached top level directory. warnings.warn('Could not any envfile.') return logger.debug('Reading environment variables from: %s', path) for line in content.splitlines(): tokens = list(shlex.shlex(line, posix=True)) # parses the assignment statement if len(tokens) < 3: continue name, op = tokens[:2] value = ''.join(tokens[2:]) if op != '=': continue if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name): continue value = value.replace(r'\n', '\n').replace(r'\t', '\t') os.environ.setdefault(name, value) for name, value in overrides.items(): os.environ.setdefault(name, value)
(path=None, **overrides)
18,375
envparse
NoValue
null
from envparse import NoValue
()
18,392
textual._log
LogGroup
A log group is a classification of the log message (*not* a level).
class LogGroup(Enum): """A log group is a classification of the log message (*not* a level).""" UNDEFINED = 0 # Mainly for testing EVENT = 1 DEBUG = 2 INFO = 3 WARNING = 4 ERROR = 5 PRINT = 6 SYSTEM = 7 LOGGING = 8 WORKER = 9
(value, names=None, *, module=None, qualname=None, type=None, start=1)
18,393
textual._log
LogVerbosity
Tags log messages as being verbose and potentially excluded from output.
class LogVerbosity(Enum): """Tags log messages as being verbose and potentially excluded from output.""" NORMAL = 0 HIGH = 1
(value, names=None, *, module=None, qualname=None, type=None, start=1)
18,394
textual
Logger
A Textual logger.
class Logger: """A Textual logger.""" def __init__( self, log_callable: LogCallable | None, group: LogGroup = LogGroup.INFO, verbosity: LogVerbosity = LogVerbosity.NORMAL, ) -> None: self._log = log_callable self._group = group self._verbosity = verbosity def __rich_repr__(self) -> rich.repr.Result: yield self._group, LogGroup.INFO yield self._verbosity, LogVerbosity.NORMAL def __call__(self, *args: object, **kwargs) -> None: if constants.LOG_FILE: output = " ".join(str(arg) for arg in args) if kwargs: key_values = " ".join( f"{key}={value!r}" for key, value in kwargs.items() ) output = f"{output} {key_values}" if output else key_values with open(constants.LOG_FILE, "a") as log_file: print(output, file=log_file) try: app = active_app.get() except LookupError: print_args = (*args, *[f"{key}={value!r}" for key, value in kwargs.items()]) print(*print_args) return if app.devtools is None or not app.devtools.is_connected: return current_frame = inspect.currentframe() assert current_frame is not None previous_frame = current_frame.f_back assert previous_frame is not None caller = inspect.getframeinfo(previous_frame) _log = self._log or app._log try: _log( self._group, self._verbosity, caller, *args, **kwargs, ) except LoggerError: # If there is not active app, try printing print_args = (*args, *[f"{key}={value!r}" for key, value in kwargs.items()]) print(*print_args) def verbosity(self, verbose: bool) -> Logger: """Get a new logger with selective verbosity. Args: verbose: True to use HIGH verbosity, otherwise NORMAL. Returns: New logger. """ verbosity = LogVerbosity.HIGH if verbose else LogVerbosity.NORMAL return Logger(self._log, self._group, verbosity) @property def verbose(self) -> Logger: """A verbose logger.""" return Logger(self._log, self._group, LogVerbosity.HIGH) @property def event(self) -> Logger: """Logs events.""" return Logger(self._log, LogGroup.EVENT) @property def debug(self) -> Logger: """Logs debug messages.""" return Logger(self._log, LogGroup.DEBUG) @property def info(self) -> Logger: """Logs information.""" return Logger(self._log, LogGroup.INFO) @property def warning(self) -> Logger: """Logs warnings.""" return Logger(self._log, LogGroup.WARNING) @property def error(self) -> Logger: """Logs errors.""" return Logger(self._log, LogGroup.ERROR) @property def system(self) -> Logger: """Logs system information.""" return Logger(self._log, LogGroup.SYSTEM) @property def logging(self) -> Logger: """Logs from stdlib logging module.""" return Logger(self._log, LogGroup.LOGGING) @property def worker(self) -> Logger: """Logs worker information.""" return Logger(self._log, LogGroup.WORKER)
(log_callable: 'LogCallable | None', group: 'LogGroup' = <LogGroup.INFO: 3>, verbosity: 'LogVerbosity' = <LogVerbosity.NORMAL: 0>) -> 'None'
18,395
textual
__call__
null
def __call__(self, *args: object, **kwargs) -> None: if constants.LOG_FILE: output = " ".join(str(arg) for arg in args) if kwargs: key_values = " ".join( f"{key}={value!r}" for key, value in kwargs.items() ) output = f"{output} {key_values}" if output else key_values with open(constants.LOG_FILE, "a") as log_file: print(output, file=log_file) try: app = active_app.get() except LookupError: print_args = (*args, *[f"{key}={value!r}" for key, value in kwargs.items()]) print(*print_args) return if app.devtools is None or not app.devtools.is_connected: return current_frame = inspect.currentframe() assert current_frame is not None previous_frame = current_frame.f_back assert previous_frame is not None caller = inspect.getframeinfo(previous_frame) _log = self._log or app._log try: _log( self._group, self._verbosity, caller, *args, **kwargs, ) except LoggerError: # If there is not active app, try printing print_args = (*args, *[f"{key}={value!r}" for key, value in kwargs.items()]) print(*print_args)
(self, *args: object, **kwargs) -> NoneType
18,396
textual
__init__
null
def __init__( self, log_callable: LogCallable | None, group: LogGroup = LogGroup.INFO, verbosity: LogVerbosity = LogVerbosity.NORMAL, ) -> None: self._log = log_callable self._group = group self._verbosity = verbosity
(self, log_callable: 'LogCallable | None', group: 'LogGroup' = <LogGroup.INFO: 3>, verbosity: 'LogVerbosity' = <LogVerbosity.NORMAL: 0>) -> 'None'
18,397
rich.repr
auto_repr
Return repr(self)
def auto( cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None ) -> Union[Type[T], Callable[[Type[T]], Type[T]]]: """Class decorator to create __repr__ from __rich_repr__""" def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]: def auto_repr(self: T) -> str: """Create repr string from __rich_repr__""" repr_str: List[str] = [] append = repr_str.append angular: bool = getattr(self.__rich_repr__, "angular", False) # type: ignore[attr-defined] for arg in self.__rich_repr__(): # type: ignore[attr-defined] if isinstance(arg, tuple): if len(arg) == 1: append(repr(arg[0])) else: key, value, *default = arg if key is None: append(repr(value)) else: if default and default[0] == value: continue append(f"{key}={value!r}") else: append(repr(arg)) if angular: return f"<{self.__class__.__name__} {' '.join(repr_str)}>" else: return f"{self.__class__.__name__}({', '.join(repr_str)})" def auto_rich_repr(self: Type[T]) -> Result: """Auto generate __rich_rep__ from signature of __init__""" try: signature = inspect.signature(self.__init__) for name, param in signature.parameters.items(): if param.kind == param.POSITIONAL_ONLY: yield getattr(self, name) elif param.kind in ( param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY, ): if param.default is param.empty: yield getattr(self, param.name) else: yield param.name, getattr(self, param.name), param.default except Exception as error: raise ReprError( f"Failed to auto generate __rich_repr__; {error}" ) from None if not hasattr(cls, "__rich_repr__"): auto_rich_repr.__doc__ = "Build a rich repr" cls.__rich_repr__ = auto_rich_repr # type: ignore[attr-defined] auto_repr.__doc__ = "Return repr(self)" cls.__repr__ = auto_repr # type: ignore[assignment] if angular is not None: cls.__rich_repr__.angular = angular # type: ignore[attr-defined] return cls if cls is None: return partial(do_replace, angular=angular) else: return do_replace(cls, angular=angular)
(self: ~T) -> str
18,398
textual
__rich_repr__
null
def __rich_repr__(self) -> rich.repr.Result: yield self._group, LogGroup.INFO yield self._verbosity, LogVerbosity.NORMAL
(self) -> Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]
18,399
textual
verbosity
Get a new logger with selective verbosity. Args: verbose: True to use HIGH verbosity, otherwise NORMAL. Returns: New logger.
def verbosity(self, verbose: bool) -> Logger: """Get a new logger with selective verbosity. Args: verbose: True to use HIGH verbosity, otherwise NORMAL. Returns: New logger. """ verbosity = LogVerbosity.HIGH if verbose else LogVerbosity.NORMAL return Logger(self._log, self._group, verbosity)
(self, verbose: bool) -> textual.Logger
18,400
textual
LoggerError
Raised when the logger failed.
class LoggerError(Exception): """Raised when the logger failed."""
null
18,401
textual
__getattr__
Lazily get the version.
def __getattr__(name: str) -> str: """Lazily get the version.""" if name == "__version__": from importlib.metadata import version return version("textual") raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
(name: str) -> str
18,423
textual._on
on
Decorator to declare that the method is a message handler. The decorator accepts an optional CSS selector that will be matched against a widget exposed by a `control` property on the message. Example: ```python # Handle the press of buttons with ID "#quit". @on(Button.Pressed, "#quit") def quit_button(self) -> None: self.app.quit() ``` Keyword arguments can be used to match additional selectors for attributes listed in [`ALLOW_SELECTOR_MATCH`][textual.message.Message.ALLOW_SELECTOR_MATCH]. Example: ```python # Handle the activation of the tab "#home" within the `TabbedContent` "#tabs". @on(TabbedContent.TabActivated, "#tabs", pane="#home") def switch_to_home(self) -> None: self.log("Switching back to the home tab.") ... ``` Args: message_type: The message type (i.e. the class). selector: An optional [selector](/guide/CSS#selectors). If supplied, the handler will only be called if `selector` matches the widget from the `control` attribute of the message. **kwargs: Additional selectors for other attributes of the message.
def on( message_type: type[Message], selector: str | None = None, **kwargs: str ) -> Callable[[DecoratedType], DecoratedType]: """Decorator to declare that the method is a message handler. The decorator accepts an optional CSS selector that will be matched against a widget exposed by a `control` property on the message. Example: ```python # Handle the press of buttons with ID "#quit". @on(Button.Pressed, "#quit") def quit_button(self) -> None: self.app.quit() ``` Keyword arguments can be used to match additional selectors for attributes listed in [`ALLOW_SELECTOR_MATCH`][textual.message.Message.ALLOW_SELECTOR_MATCH]. Example: ```python # Handle the activation of the tab "#home" within the `TabbedContent` "#tabs". @on(TabbedContent.TabActivated, "#tabs", pane="#home") def switch_to_home(self) -> None: self.log("Switching back to the home tab.") ... ``` Args: message_type: The message type (i.e. the class). selector: An optional [selector](/guide/CSS#selectors). If supplied, the handler will only be called if `selector` matches the widget from the `control` attribute of the message. **kwargs: Additional selectors for other attributes of the message. """ selectors: dict[str, str] = {} if selector is not None: selectors["control"] = selector if kwargs: selectors.update(kwargs) parsed_selectors: dict[str, tuple[SelectorSet, ...]] = {} for attribute, css_selector in selectors.items(): if attribute == "control": if message_type.control == Message.control: raise OnDecoratorError( "The message class must have a 'control' to match with the on decorator" ) elif attribute not in message_type.ALLOW_SELECTOR_MATCH: raise OnDecoratorError( f"The attribute {attribute!r} can't be matched; have you added it to " + f"{message_type.__name__}.ALLOW_SELECTOR_MATCH?" ) try: parsed_selectors[attribute] = parse_selectors(css_selector) except TokenError: raise OnDecoratorError( f"Unable to parse selector {css_selector!r} for {attribute}; check for syntax errors" ) from None def decorator(method: DecoratedType) -> DecoratedType: """Store message and selector in function attribute, return callable unaltered.""" if not hasattr(method, "_textual_on"): setattr(method, "_textual_on", []) getattr(method, "_textual_on").append((message_type, parsed_selectors)) return method return decorator
(message_type: type[textual.message.Message], selector: Optional[str] = None, **kwargs: str) -> Callable[[~DecoratedType], ~DecoratedType]
18,424
textual
panic
null
def panic(*args: RenderableType) -> None: from ._context import active_app app = active_app.get() app.panic(*args)
(*args: Union[rich.console.ConsoleRenderable, rich.console.RichCast, str]) -> NoneType
18,428
textual._work_decorator
work
A decorator used to create [workers](/guide/workers). Args: method: A function or coroutine. name: A short string to identify the worker (in logs and debugging). group: A short string to identify a group of workers. exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions. exclusive: Cancel all workers in the same group. description: Readable description of the worker for debugging purposes. By default, it uses a string representation of the decorated method and its arguments. thread: Mark the method as a thread worker.
def work( method: ( Callable[FactoryParamSpec, ReturnType] | Callable[FactoryParamSpec, Coroutine[None, None, ReturnType]] | None ) = None, *, name: str = "", group: str = "default", exit_on_error: bool = True, exclusive: bool = False, description: str | None = None, thread: bool = False, ) -> Callable[FactoryParamSpec, Worker[ReturnType]] | Decorator: """A decorator used to create [workers](/guide/workers). Args: method: A function or coroutine. name: A short string to identify the worker (in logs and debugging). group: A short string to identify a group of workers. exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions. exclusive: Cancel all workers in the same group. description: Readable description of the worker for debugging purposes. By default, it uses a string representation of the decorated method and its arguments. thread: Mark the method as a thread worker. """ def decorator( method: ( Callable[DecoratorParamSpec, ReturnType] | Callable[DecoratorParamSpec, Coroutine[None, None, ReturnType]] ) ) -> Callable[DecoratorParamSpec, Worker[ReturnType]]: """The decorator.""" # Methods that aren't async *must* be marked as being a thread # worker. if not iscoroutinefunction(method) and not thread: raise WorkerDeclarationError( "Can not create a worker from a non-async function unless `thread=True` is set on the work decorator." ) @wraps(method) def decorated( *args: DecoratorParamSpec.args, **kwargs: DecoratorParamSpec.kwargs ) -> Worker[ReturnType]: """The replaced callable.""" from .dom import DOMNode self = args[0] assert isinstance(self, DOMNode) if description is not None: debug_description = description else: try: positional_arguments = ", ".join(repr(arg) for arg in args[1:]) keyword_arguments = ", ".join( f"{name}={value!r}" for name, value in kwargs.items() ) tokens = [positional_arguments, keyword_arguments] debug_description = f"{method.__name__}({', '.join(token for token in tokens if token)})" except Exception: debug_description = "<worker>" worker = cast( "Worker[ReturnType]", self.run_worker( partial(method, *args, **kwargs), name=name or method.__name__, group=group, description=debug_description, exclusive=exclusive, exit_on_error=exit_on_error, thread=thread, ), ) return worker return decorated if method is None: return decorator else: return decorator(method)
(method: 'Callable[FactoryParamSpec, ReturnType] | Callable[FactoryParamSpec, Coroutine[None, None, ReturnType]] | None' = None, *, name: 'str' = '', group: 'str' = 'default', exit_on_error: 'bool' = True, exclusive: 'bool' = False, description: 'str | None' = None, thread: 'bool' = False) -> 'Callable[FactoryParamSpec, Worker[ReturnType]] | Decorator'
18,429
asynch.connection
connect
null
def _parse_dsn(self, url): """ Return a client configured from the given URL. For example:: clickhouse://[user:password]@localhost:9000/default clickhouses://[user:password]@localhost:9440/default Three URL schemes are supported: clickhouse:// creates a normal TCP socket connection clickhouses:// creates a SSL wrapped TCP socket connection Any additional querystring arguments will be passed along to the Connection class's initializer. """ url = urlparse(url) settings = {} kwargs = {} if url.hostname is not None: self._host = kwargs["host"] = unquote(url.hostname) if url.port is not None: self._port = kwargs["port"] = url.port path = url.path.replace("/", "", 1) if path: self._database = kwargs["database"] = path if url.username is not None: self._user = kwargs["user"] = unquote(url.username) if url.password is not None: self._password = kwargs["password"] = unquote(url.password) if url.scheme == "clickhouses": kwargs["secure"] = True compression_algs = {"lz4", "lz4hc", "zstd"} timeouts = {"connect_timeout", "send_receive_timeout", "sync_request_timeout"} for name, value in parse_qs(url.query).items(): if not value or not len(value): continue value = value[0] if name == "compression": value = value.lower() if value in compression_algs: kwargs[name] = value else: kwargs[name] = asbool(value) elif name == "secure": kwargs[name] = asbool(value) elif name == "client_name": kwargs[name] = value elif name in timeouts: kwargs[name] = float(value) elif name == "compress_block_size": kwargs[name] = int(value) # ssl elif name == "verify": kwargs[name] = asbool(value) elif name == "ssl_version": kwargs[name] = getattr(ssl, value) elif name in ["ca_certs", "ciphers"]: kwargs[name] = value elif name == "alt_hosts": kwargs["alt_hosts"] = value else: settings[name] = value if settings: kwargs["settings"] = settings return kwargs
(dsn: Optional[str] = None, host: str = '127.0.0.1', port: int = 9000, database: str = 'default', user: str = 'default', password: str = '', cursor_cls=<class 'asynch.cursors.Cursor'>, echo=False, **kwargs) -> asynch.connection.Connection
18,431
asynch.pool
create_pool
null
def create_pool(minsize: int = 1, maxsize: int = 10, loop=None, **kwargs): coro = _create_pool(minsize=minsize, maxsize=maxsize, loop=loop, **kwargs) return _PoolContextManager(coro)
(minsize: int = 1, maxsize: int = 10, loop=None, **kwargs)
18,436
miarec_s3fs.s3fs
S3FS
Construct an Amazon S3 filesystem for `PyFilesystem <https://pyfilesystem.org>`_ :param str bucket_name: The S3 bucket name. :param str dir_path: The root directory within the S3 Bucket. Defaults to ``"/"`` :param str aws_access_key_id: The access key, or ``None`` to read the key from standard configuration files. :param str aws_secret_access_key: The secret key, or ``None`` to read the key from standard configuration files. :param str endpoint_url: Alternative endpoint url (``None`` to use default). :param str aws_session_token: :param str region: Optional S3 region. :param str delimiter: The delimiter to separate folders, defaults to a forward slash. :param bool strict: When ``True`` (default) S3FS will follow the PyFilesystem specification exactly. Set to ``False`` to disable validation of destination paths which may speed up uploads / downloads. :param str cache_control: Sets the 'Cache-Control' header for uploads. :param str acl: Sets the Access Control List header for uploads. :param dict upload_args: A dictionary for additional upload arguments. See https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.put for details. :param dict download_args: Dictionary of extra arguments passed to the S3 client. :param dict config_args: Advanced S3 client configuration options. See https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
class S3FS(FS): """ Construct an Amazon S3 filesystem for `PyFilesystem <https://pyfilesystem.org>`_ :param str bucket_name: The S3 bucket name. :param str dir_path: The root directory within the S3 Bucket. Defaults to ``"/"`` :param str aws_access_key_id: The access key, or ``None`` to read the key from standard configuration files. :param str aws_secret_access_key: The secret key, or ``None`` to read the key from standard configuration files. :param str endpoint_url: Alternative endpoint url (``None`` to use default). :param str aws_session_token: :param str region: Optional S3 region. :param str delimiter: The delimiter to separate folders, defaults to a forward slash. :param bool strict: When ``True`` (default) S3FS will follow the PyFilesystem specification exactly. Set to ``False`` to disable validation of destination paths which may speed up uploads / downloads. :param str cache_control: Sets the 'Cache-Control' header for uploads. :param str acl: Sets the Access Control List header for uploads. :param dict upload_args: A dictionary for additional upload arguments. See https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.put for details. :param dict download_args: Dictionary of extra arguments passed to the S3 client. :param dict config_args: Advanced S3 client configuration options. See https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """ _meta = { "case_insensitive": False, "invalid_path_chars": "\0", "network": True, "read_only": False, "thread_safe": True, "unicode_paths": True, "virtual": False, } _object_attributes = [ "accept_ranges", "cache_control", "content_disposition", "content_encoding", "content_language", "content_length", "content_type", "delete_marker", "e_tag", "expiration", "expires", "last_modified", "metadata", "missing_meta", "parts_count", "replication_status", "request_charged", "restore", "server_side_encryption", "sse_customer_algorithm", "sse_customer_key_md5", "ssekms_key_id", "storage_class", "version_id", "website_redirect_location", ] def __init__( self, bucket_name, dir_path="/", aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None, region=None, delimiter="/", strict=True, cache_control=None, acl=None, upload_args=None, download_args=None, config_args=None, ): _creds = (aws_access_key_id, aws_secret_access_key) if any(_creds) and not all(_creds): raise ValueError( "aws_access_key_id and aws_secret_access_key " "must be set together if specified" ) self._bucket_name = bucket_name self.dir_path = dir_path self._prefix = relpath(normpath(dir_path)).rstrip("/") self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.aws_session_token = aws_session_token self.endpoint_url = endpoint_url self.region = region self.delimiter = delimiter self.strict = strict self._tlocal = threading.local() if cache_control or acl: upload_args = upload_args or {} if cache_control: upload_args["CacheControl"] = cache_control if acl: upload_args["ACL"] = acl self.upload_args = upload_args self.download_args = download_args self.config_args = config_args super(S3FS, self).__init__() def __repr__(self): return _make_repr( self.__class__.__name__, self._bucket_name, dir_path=(self.dir_path, "/"), region=(self.region, None), delimiter=(self.delimiter, "/"), ) def __str__(self): return "<s3fs '{}'>".format(join(self._bucket_name, relpath(self.dir_path))) def _path_to_key(self, path): """Converts an fs path to a s3 key.""" _path = relpath(normpath(path)) _key = ( "{}/{}".format(self._prefix, _path).lstrip("/").replace("/", self.delimiter) ) return _key def _path_to_dir_key(self, path): """Converts an fs path to a s3 key.""" _path = relpath(normpath(path)) _key = ( forcedir("{}/{}".format(self._prefix, _path)) .lstrip("/") .replace("/", self.delimiter) ) return _key def _key_to_path(self, key): return key.replace(self.delimiter, "/") def _get_object(self, path, key): _key = key.rstrip(self.delimiter) try: with s3errors(path): obj = self.s3.Object(self._bucket_name, _key) obj.load() except errors.ResourceNotFound: with s3errors(path): obj = self.s3.Object(self._bucket_name, _key + self.delimiter) obj.load() return obj else: return obj def _get_upload_args(self, key): upload_args = self.upload_args.copy() if self.upload_args else {} if "ContentType" not in upload_args: mime_type, _encoding = mimetypes.guess_type(key) upload_args["ContentType"] = mime_type or "binary/octet-stream" return upload_args @property def s3_session(self): if not hasattr(self._tlocal, 's3_session'): self._tlocal.s3_session = boto3.Session() return self._tlocal.s3_session @property def s3(self): config = Config(**self.config_args) if self.config_args else None if not hasattr(self._tlocal, "s3"): self._tlocal.s3 = self.s3_session.resource( "s3", region_name=self.region, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, aws_session_token=self.aws_session_token, endpoint_url=self.endpoint_url, config=config, ) return self._tlocal.s3 @property def client(self): if not hasattr(self._tlocal, "client"): config = Config(**self.config_args) if self.config_args else None self._tlocal.client = self.s3_session.client( "s3", region_name=self.region, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, aws_session_token=self.aws_session_token, endpoint_url=self.endpoint_url, config=config, ) return self._tlocal.client def _info_from_object(self, obj, namespaces): """Make an info dict from an s3 Object.""" key = obj.key path = self._key_to_path(key) name = basename(path.rstrip("/")) is_dir = key.endswith(self.delimiter) info = {"basic": {"name": name, "is_dir": is_dir}} if "details" in namespaces: _type = int(ResourceType.directory if is_dir else ResourceType.file) info["details"] = { "accessed": None, "modified": datetime_to_epoch(obj.last_modified), "size": obj.content_length, "type": _type, } if "s3" in namespaces: s3info = info["s3"] = {} for name in self._object_attributes: value = getattr(obj, name, None) if isinstance(value, datetime): value = datetime_to_epoch(value) s3info[name] = value if "urls" in namespaces: url = self.client.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": self._bucket_name, "Key": key}, ) info["urls"] = {"download": url} return info def isdir(self, path): _path = self.validatepath(path) try: return self._getinfo(_path).is_dir except errors.ResourceNotFound: return False def getinfo(self, path, namespaces=None): self.check() namespaces = namespaces or () _path = self.validatepath(path) _key = self._path_to_key(_path) try: dir_path = dirname(_path) if dir_path != "/": _dir_key = self._path_to_dir_key(dir_path) with s3errors(path): obj = self.s3.Object(self._bucket_name, _dir_key) obj.load() except errors.ResourceNotFound: raise errors.ResourceNotFound(path) if _path == "/": return Info( { "basic": {"name": "", "is_dir": True}, "details": {"type": int(ResourceType.directory)}, } ) obj = self._get_object(path, _key) info = self._info_from_object(obj, namespaces) return Info(info) def _getinfo(self, path, namespaces=None): """Gets info without checking for parent dir.""" namespaces = namespaces or () _path = self.validatepath(path) _key = self._path_to_key(_path) if _path == "/": return Info( { "basic": {"name": "", "is_dir": True}, "details": {"type": int(ResourceType.directory)}, } ) obj = self._get_object(path, _key) info = self._info_from_object(obj, namespaces) return Info(info) def listdir(self, path): _path = self.validatepath(path) _s3_key = self._path_to_dir_key(_path) prefix_len = len(_s3_key) paginator = self.client.get_paginator("list_objects") with s3errors(path): _paginate = paginator.paginate( Bucket=self._bucket_name, Prefix=_s3_key, Delimiter=self.delimiter ) _directory = [] for result in _paginate: common_prefixes = result.get("CommonPrefixes", ()) for prefix in common_prefixes: _prefix = prefix.get("Prefix") _name = _prefix[prefix_len:] if _name: _directory.append(_name.rstrip(self.delimiter)) for obj in result.get("Contents", ()): name = obj["Key"][prefix_len:] if name: _directory.append(name) if not _directory: if not self.getinfo(_path).is_dir: raise errors.DirectoryExpected(path) return _directory def makedir(self, path, permissions=None, recreate=False): self.check() _path = self.validatepath(path) _key = self._path_to_dir_key(_path) if not self.isdir(dirname(_path)): raise errors.ResourceNotFound(path) try: self._getinfo(path) except errors.ResourceNotFound: pass else: if recreate: return self.opendir(_path) else: raise errors.DirectoryExists(path) with s3errors(path): _obj = self.s3.Object(self._bucket_name, _key) _obj.put(**self._get_upload_args(_key)) return SubFS(self, path) def openbin(self, path, mode="rb", buffering=-1, **options): _mode = Mode(mode) _mode.validate_bin() self.check() _path = self.validatepath(path) _key = self._path_to_key(_path) if _mode.create: def on_close_create(s3file): """Called when the S3 file closes, to upload data.""" try: s3file.raw.seek(0) with s3errors(path): self.client.upload_fileobj( s3file.raw, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), ) finally: s3file.raw.close() try: dir_path = dirname(_path) if dir_path != "/": _dir_key = self._path_to_dir_key(dir_path) self._get_object(dir_path, _dir_key) except errors.ResourceNotFound: raise errors.ResourceNotFound(path) try: info = self._getinfo(path) except errors.ResourceNotFound: pass else: if _mode.exclusive: raise errors.FileExists(path) if info.is_dir: raise errors.FileExpected(path) s3file = S3File.factory( path, _mode.to_platform_bin(), on_close=on_close_create ) if _mode.appending: try: with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, s3file.raw, ExtraArgs=self.download_args, ) except errors.ResourceNotFound: pass else: s3file.seek(0, os.SEEK_END) return s3file if self.strict: info = self.getinfo(path) if info.is_dir: raise errors.FileExpected(path) def on_close(s3file): """Called when the S3 file closes, to upload the data.""" try: if _mode.writing: s3file.raw.seek(0, os.SEEK_SET) with s3errors(path): self.client.upload_fileobj( s3file.raw, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), ) finally: s3file.raw.close() s3file = S3File.factory( path, _mode.to_platform_bin(), on_close=on_close ) with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, s3file.raw, ExtraArgs=self.download_args ) s3file.seek(0, os.SEEK_SET) return s3file def remove(self, path): self.check() _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: info = self.getinfo(path) if info.is_dir: raise errors.FileExpected(path) with s3errors(path): self.client.delete_object(Bucket=self._bucket_name, Key=_key) def isempty(self, path): self.check() _path = self.validatepath(path) _key = self._path_to_dir_key(_path) response = self.client.list_objects( Bucket=self._bucket_name, Prefix=_key, MaxKeys=2 ) contents = response.get("Contents", ()) for obj in contents: if obj["Key"] != _key: return False return True def removedir(self, path): self.check() _path = self.validatepath(path) if _path == "/": raise errors.RemoveRootError() info = self.getinfo(_path) if not info.is_dir: raise errors.DirectoryExpected(path) if not self.isempty(path): raise errors.DirectoryNotEmpty(path) _key = self._path_to_dir_key(_path) self.client.delete_object(Bucket=self._bucket_name, Key=_key) def setinfo(self, path, info): self.getinfo(path) def readbytes(self, path): self.check() if self.strict: info = self.getinfo(path) if not info.is_file: raise errors.FileExpected(path) _path = self.validatepath(path) _key = self._path_to_key(_path) bytes_file = io.BytesIO() with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, bytes_file, ExtraArgs=self.download_args ) return bytes_file.getvalue() def download(self, path, file, chunk_size=None, **options): self.check() if self.strict: info = self.getinfo(path) if not info.is_file: raise errors.FileExpected(path) _path = self.validatepath(path) _key = self._path_to_key(_path) with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, file, ExtraArgs=self.download_args ) def exists(self, path): self.check() _path = self.validatepath(path) if _path == "/": return True _key = self._path_to_dir_key(_path) try: self._get_object(path, _key) except errors.ResourceNotFound: return False else: return True def scandir(self, path, namespaces=None, page=None): _path = self.validatepath(path) namespaces = namespaces or () _s3_key = self._path_to_dir_key(_path) prefix_len = len(_s3_key) info = self.getinfo(path) if not info.is_dir: raise errors.DirectoryExpected(path) paginator = self.client.get_paginator("list_objects") _paginate = paginator.paginate( Bucket=self._bucket_name, Prefix=_s3_key, Delimiter=self.delimiter ) def gen_info(): for result in _paginate: common_prefixes = result.get("CommonPrefixes", ()) for prefix in common_prefixes: _prefix = prefix.get("Prefix") _name = _prefix[prefix_len:] if _name: info = { "basic": { "name": _name.rstrip(self.delimiter), "is_dir": True, } } yield Info(info) for _obj in result.get("Contents", ()): name = _obj["Key"][prefix_len:] if name: with s3errors(path): obj = self.s3.Object(self._bucket_name, _obj["Key"]) info = self._info_from_object(obj, namespaces) yield Info(info) iter_info = iter(gen_info()) if page is not None: start, end = page iter_info = itertools.islice(iter_info, start, end) for info in iter_info: yield info def writebytes(self, path, contents): if not isinstance(contents, bytes): raise TypeError("contents must be bytes") _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: if not self.isdir(dirname(path)): raise errors.ResourceNotFound(path) try: info = self._getinfo(path) if info.is_dir: raise errors.FileExpected(path) except errors.ResourceNotFound: pass bytes_file = io.BytesIO(contents) with s3errors(path): self.client.upload_fileobj( bytes_file, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), ) def upload(self, path, file, chunk_size=None, **options): _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: if not self.isdir(dirname(path)): raise errors.ResourceNotFound(path) try: info = self._getinfo(path) if info.is_dir: raise errors.FileExpected(path) except errors.ResourceNotFound: pass with s3errors(path): self.client.upload_fileobj( file, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key) ) def copy(self, src_path, dst_path, overwrite=False, preserve_time=False): if not overwrite and self.exists(dst_path): raise errors.DestinationExists(dst_path) _src_path = self.validatepath(src_path) _dst_path = self.validatepath(dst_path) if self.strict: if not self.isdir(dirname(_dst_path)): raise errors.ResourceNotFound(dst_path) _src_key = self._path_to_key(_src_path) _dst_key = self._path_to_key(_dst_path) try: with s3errors(src_path): self.client.copy_object( Bucket=self._bucket_name, Key=_dst_key, CopySource={"Bucket": self._bucket_name, "Key": _src_key}, **self._get_upload_args(_src_key) ) except errors.ResourceNotFound: if self.exists(src_path): raise errors.FileExpected(src_path) raise def move(self, src_path, dst_path, overwrite=False, preserve_time=False): self.copy(src_path, dst_path, overwrite=overwrite, preserve_time=preserve_time) self.remove(src_path) def geturl(self, path, purpose="download"): _path = self.validatepath(path) _key = self._path_to_key(_path) if _path == "/": raise errors.NoURL(path, purpose) if purpose == "download": url = self.client.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": self._bucket_name, "Key": _key}, ) return url else: raise errors.NoURL(path, purpose)
(bucket_name, dir_path='/', aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None, region=None, delimiter='/', strict=True, cache_control=None, acl=None, upload_args=None, download_args=None, config_args=None)
18,437
fs.base
__del__
Auto-close the filesystem on exit.
def __del__(self): """Auto-close the filesystem on exit.""" self.close()
(self)
18,438
fs.base
__enter__
Allow use of filesystem as a context manager.
def __enter__(self): # type: (...) -> FS """Allow use of filesystem as a context manager.""" return self
(self)
18,439
fs.base
__exit__
Close filesystem on exit.
def __exit__( self, exc_type, # type: Optional[Type[BaseException]] exc_value, # type: Optional[BaseException] traceback, # type: Optional[TracebackType] ): # type: (...) -> None """Close filesystem on exit.""" self.close()
(self, exc_type, exc_value, traceback)
18,440
miarec_s3fs.s3fs
__init__
null
def __init__( self, bucket_name, dir_path="/", aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None, region=None, delimiter="/", strict=True, cache_control=None, acl=None, upload_args=None, download_args=None, config_args=None, ): _creds = (aws_access_key_id, aws_secret_access_key) if any(_creds) and not all(_creds): raise ValueError( "aws_access_key_id and aws_secret_access_key " "must be set together if specified" ) self._bucket_name = bucket_name self.dir_path = dir_path self._prefix = relpath(normpath(dir_path)).rstrip("/") self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.aws_session_token = aws_session_token self.endpoint_url = endpoint_url self.region = region self.delimiter = delimiter self.strict = strict self._tlocal = threading.local() if cache_control or acl: upload_args = upload_args or {} if cache_control: upload_args["CacheControl"] = cache_control if acl: upload_args["ACL"] = acl self.upload_args = upload_args self.download_args = download_args self.config_args = config_args super(S3FS, self).__init__()
(self, bucket_name, dir_path='/', aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None, region=None, delimiter='/', strict=True, cache_control=None, acl=None, upload_args=None, download_args=None, config_args=None)
18,441
miarec_s3fs.s3fs
__repr__
null
def __repr__(self): return _make_repr( self.__class__.__name__, self._bucket_name, dir_path=(self.dir_path, "/"), region=(self.region, None), delimiter=(self.delimiter, "/"), )
(self)
18,442
miarec_s3fs.s3fs
__str__
null
def __str__(self): return "<s3fs '{}'>".format(join(self._bucket_name, relpath(self.dir_path)))
(self)
18,443
miarec_s3fs.s3fs
_get_object
null
def _get_object(self, path, key): _key = key.rstrip(self.delimiter) try: with s3errors(path): obj = self.s3.Object(self._bucket_name, _key) obj.load() except errors.ResourceNotFound: with s3errors(path): obj = self.s3.Object(self._bucket_name, _key + self.delimiter) obj.load() return obj else: return obj
(self, path, key)
18,444
miarec_s3fs.s3fs
_get_upload_args
null
def _get_upload_args(self, key): upload_args = self.upload_args.copy() if self.upload_args else {} if "ContentType" not in upload_args: mime_type, _encoding = mimetypes.guess_type(key) upload_args["ContentType"] = mime_type or "binary/octet-stream" return upload_args
(self, key)
18,445
miarec_s3fs.s3fs
_getinfo
Gets info without checking for parent dir.
def _getinfo(self, path, namespaces=None): """Gets info without checking for parent dir.""" namespaces = namespaces or () _path = self.validatepath(path) _key = self._path_to_key(_path) if _path == "/": return Info( { "basic": {"name": "", "is_dir": True}, "details": {"type": int(ResourceType.directory)}, } ) obj = self._get_object(path, _key) info = self._info_from_object(obj, namespaces) return Info(info)
(self, path, namespaces=None)