prompt_id int64 0 941 | project stringclasses 24 values | module stringlengths 7 49 | class stringlengths 0 32 | method stringlengths 2 37 | focal_method_txt stringlengths 43 41.5k | focal_method_lines listlengths 2 2 | in_stack bool 2 classes | globals listlengths 0 16 | type_context stringlengths 79 41.9k | has_branch bool 2 classes | total_branches int64 0 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|
745 | tornado | tornado.simple_httpclient | _HTTPConnection | on_connection_close | def on_connection_close(self) -> None:
if self.final_callback is not None:
message = "Connection closed"
if self.stream.error:
raise self.stream.error
try:
raise HTTPStreamClosedError(message)
except HTTPStreamClosedError:
self._handle_exception(*sys.exc_info()) | [
577,
585
] | false | [] | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.ioloop import IOLoop
from tornado.iostream import StreamClosedError, IOStream
from tornado.netutil import (
Resolver,
OverrideResolver,
_client_ssl_defaults,
is_valid_ip,
)
from tornado.log import gen_log
from tornado.tcpclient import TCPClient
import base64
import collections
import copy
import functools
import re
import socket
import ssl
import sys
import time
from io import BytesIO
import urllib.parse
from typing import Dict, Any, Callable, Optional, Type, Union
from types import TracebackType
import typing
class HTTPStreamClosedError(HTTPError):
def __init__(self, message: str) -> None:
super().__init__(599, message=message)
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
)
def __init__(
self,
client: Optional[SimpleAsyncHTTPClient],
request: HTTPRequest,
release_callback: Callable[[], None],
final_callback: Callable[[HTTPResponse], None],
max_buffer_size: int,
tcp_client: TCPClient,
max_header_size: int,
max_body_size: int,
) -> None:
self.io_loop = IOLoop.current()
self.start_time = self.io_loop.time()
self.start_wall_time = time.time()
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None # type: Optional[int]
self.headers = None # type: Optional[httputil.HTTPHeaders]
self.chunks = [] # type: List[bytes]
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None # type: object
self._sockaddr = None
IOLoop.current().add_future(
gen.convert_yielded(self.run()), lambda f: f.result()
)
def on_connection_close(self) -> None:
if self.final_callback is not None:
message = "Connection closed"
if self.stream.error:
raise self.stream.error
try:
raise HTTPStreamClosedError(message)
except HTTPStreamClosedError:
self._handle_exception(*sys.exc_info()) | true | 2 |
746 | tornado | tornado.simple_httpclient | _HTTPConnection | headers_received | async def headers_received(
self,
first_line: Union[httputil.ResponseStartLine, httputil.RequestStartLine],
headers: httputil.HTTPHeaders,
) -> None:
assert isinstance(first_line, httputil.ResponseStartLine)
if self.request.expect_100_continue and first_line.code == 100:
await self._write_body(False)
return
self.code = first_line.code
self.reason = first_line.reason
self.headers = headers
if self._should_follow_redirect():
return
if self.request.header_callback is not None:
# Reassemble the start line.
self.request.header_callback("%s %s %s\r\n" % first_line)
for k, v in self.headers.get_all():
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback("\r\n") | [
587,
608
] | false | [] | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.ioloop import IOLoop
from tornado.iostream import StreamClosedError, IOStream
from tornado.netutil import (
Resolver,
OverrideResolver,
_client_ssl_defaults,
is_valid_ip,
)
from tornado.log import gen_log
from tornado.tcpclient import TCPClient
import base64
import collections
import copy
import functools
import re
import socket
import ssl
import sys
import time
from io import BytesIO
import urllib.parse
from typing import Dict, Any, Callable, Optional, Type, Union
from types import TracebackType
import typing
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
)
def __init__(
self,
client: Optional[SimpleAsyncHTTPClient],
request: HTTPRequest,
release_callback: Callable[[], None],
final_callback: Callable[[HTTPResponse], None],
max_buffer_size: int,
tcp_client: TCPClient,
max_header_size: int,
max_body_size: int,
) -> None:
self.io_loop = IOLoop.current()
self.start_time = self.io_loop.time()
self.start_wall_time = time.time()
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None # type: Optional[int]
self.headers = None # type: Optional[httputil.HTTPHeaders]
self.chunks = [] # type: List[bytes]
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None # type: object
self._sockaddr = None
IOLoop.current().add_future(
gen.convert_yielded(self.run()), lambda f: f.result()
)
async def headers_received(
self,
first_line: Union[httputil.ResponseStartLine, httputil.RequestStartLine],
headers: httputil.HTTPHeaders,
) -> None:
assert isinstance(first_line, httputil.ResponseStartLine)
if self.request.expect_100_continue and first_line.code == 100:
await self._write_body(False)
return
self.code = first_line.code
self.reason = first_line.reason
self.headers = headers
if self._should_follow_redirect():
return
if self.request.header_callback is not None:
# Reassemble the start line.
self.request.header_callback("%s %s %s\r\n" % first_line)
for k, v in self.headers.get_all():
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback("\r\n") | true | 2 |
747 | tornado | tornado.simple_httpclient | _HTTPConnection | finish | def finish(self) -> None:
assert self.code is not None
data = b"".join(self.chunks)
self._remove_timeout()
original_request = getattr(self.request, "original_request", self.request)
if self._should_follow_redirect():
assert isinstance(self.request, _RequestProxy)
new_request = copy.copy(self.request.request)
new_request.url = urllib.parse.urljoin(
self.request.url, self.headers["Location"]
)
new_request.max_redirects = self.request.max_redirects - 1
del new_request.headers["Host"]
# https://tools.ietf.org/html/rfc7231#section-6.4
#
# The original HTTP spec said that after a 301 or 302
# redirect, the request method should be preserved.
# However, browsers implemented this by changing the
# method to GET, and the behavior stuck. 303 redirects
# always specified this POST-to-GET behavior, arguably
# for *all* methods, but libcurl < 7.70 only does this
# for POST, while libcurl >= 7.70 does it for other methods.
if (self.code == 303 and self.request.method != "HEAD") or (
self.code in (301, 302) and self.request.method == "POST"
):
new_request.method = "GET"
new_request.body = None
for h in [
"Content-Length",
"Content-Type",
"Content-Encoding",
"Transfer-Encoding",
]:
try:
del self.request.headers[h]
except KeyError:
pass
new_request.original_request = original_request
final_callback = self.final_callback
self.final_callback = None
self._release()
fut = self.client.fetch(new_request, raise_error=False)
fut.add_done_callback(lambda f: final_callback(f.result()))
self._on_end_request()
return
if self.request.streaming_callback:
buffer = BytesIO()
else:
buffer = BytesIO(data) # TODO: don't require one big string?
response = HTTPResponse(
original_request,
self.code,
reason=getattr(self, "reason", None),
headers=self.headers,
request_time=self.io_loop.time() - self.start_time,
start_time=self.start_wall_time,
buffer=buffer,
effective_url=self.request.url,
)
self._run_callback(response)
self._on_end_request() | [
621,
681
] | false | [] | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.ioloop import IOLoop
from tornado.iostream import StreamClosedError, IOStream
from tornado.netutil import (
Resolver,
OverrideResolver,
_client_ssl_defaults,
is_valid_ip,
)
from tornado.log import gen_log
from tornado.tcpclient import TCPClient
import base64
import collections
import copy
import functools
import re
import socket
import ssl
import sys
import time
from io import BytesIO
import urllib.parse
from typing import Dict, Any, Callable, Optional, Type, Union
from types import TracebackType
import typing
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
)
def __init__(
self,
client: Optional[SimpleAsyncHTTPClient],
request: HTTPRequest,
release_callback: Callable[[], None],
final_callback: Callable[[HTTPResponse], None],
max_buffer_size: int,
tcp_client: TCPClient,
max_header_size: int,
max_body_size: int,
) -> None:
self.io_loop = IOLoop.current()
self.start_time = self.io_loop.time()
self.start_wall_time = time.time()
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None # type: Optional[int]
self.headers = None # type: Optional[httputil.HTTPHeaders]
self.chunks = [] # type: List[bytes]
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None # type: object
self._sockaddr = None
IOLoop.current().add_future(
gen.convert_yielded(self.run()), lambda f: f.result()
)
def finish(self) -> None:
assert self.code is not None
data = b"".join(self.chunks)
self._remove_timeout()
original_request = getattr(self.request, "original_request", self.request)
if self._should_follow_redirect():
assert isinstance(self.request, _RequestProxy)
new_request = copy.copy(self.request.request)
new_request.url = urllib.parse.urljoin(
self.request.url, self.headers["Location"]
)
new_request.max_redirects = self.request.max_redirects - 1
del new_request.headers["Host"]
# https://tools.ietf.org/html/rfc7231#section-6.4
#
# The original HTTP spec said that after a 301 or 302
# redirect, the request method should be preserved.
# However, browsers implemented this by changing the
# method to GET, and the behavior stuck. 303 redirects
# always specified this POST-to-GET behavior, arguably
# for *all* methods, but libcurl < 7.70 only does this
# for POST, while libcurl >= 7.70 does it for other methods.
if (self.code == 303 and self.request.method != "HEAD") or (
self.code in (301, 302) and self.request.method == "POST"
):
new_request.method = "GET"
new_request.body = None
for h in [
"Content-Length",
"Content-Type",
"Content-Encoding",
"Transfer-Encoding",
]:
try:
del self.request.headers[h]
except KeyError:
pass
new_request.original_request = original_request
final_callback = self.final_callback
self.final_callback = None
self._release()
fut = self.client.fetch(new_request, raise_error=False)
fut.add_done_callback(lambda f: final_callback(f.result()))
self._on_end_request()
return
if self.request.streaming_callback:
buffer = BytesIO()
else:
buffer = BytesIO(data) # TODO: don't require one big string?
response = HTTPResponse(
original_request,
self.code,
reason=getattr(self, "reason", None),
headers=self.headers,
request_time=self.io_loop.time() - self.start_time,
start_time=self.start_wall_time,
buffer=buffer,
effective_url=self.request.url,
)
self._run_callback(response)
self._on_end_request() | true | 2 |
748 | tornado | tornado.simple_httpclient | _HTTPConnection | data_received | def data_received(self, chunk: bytes) -> None:
if self._should_follow_redirect():
# We're going to follow a redirect so just discard the body.
return
if self.request.streaming_callback is not None:
self.request.streaming_callback(chunk)
else:
self.chunks.append(chunk) | [
686,
693
] | false | [] | from tornado.escape import _unicode
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
AsyncHTTPClient,
main,
_RequestProxy,
HTTPRequest,
)
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.ioloop import IOLoop
from tornado.iostream import StreamClosedError, IOStream
from tornado.netutil import (
Resolver,
OverrideResolver,
_client_ssl_defaults,
is_valid_ip,
)
from tornado.log import gen_log
from tornado.tcpclient import TCPClient
import base64
import collections
import copy
import functools
import re
import socket
import ssl
import sys
import time
from io import BytesIO
import urllib.parse
from typing import Dict, Any, Callable, Optional, Type, Union
from types import TracebackType
import typing
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
)
def __init__(
self,
client: Optional[SimpleAsyncHTTPClient],
request: HTTPRequest,
release_callback: Callable[[], None],
final_callback: Callable[[HTTPResponse], None],
max_buffer_size: int,
tcp_client: TCPClient,
max_header_size: int,
max_body_size: int,
) -> None:
self.io_loop = IOLoop.current()
self.start_time = self.io_loop.time()
self.start_wall_time = time.time()
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None # type: Optional[int]
self.headers = None # type: Optional[httputil.HTTPHeaders]
self.chunks = [] # type: List[bytes]
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None # type: object
self._sockaddr = None
IOLoop.current().add_future(
gen.convert_yielded(self.run()), lambda f: f.result()
)
def data_received(self, chunk: bytes) -> None:
if self._should_follow_redirect():
# We're going to follow a redirect so just discard the body.
return
if self.request.streaming_callback is not None:
self.request.streaming_callback(chunk)
else:
self.chunks.append(chunk) | true | 2 |
749 | tornado | tornado.tcpclient | _Connector | __init__ | def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set() | [
54,
72
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set() | false | 0 |
750 | tornado | tornado.tcpclient | _Connector | split | @staticmethod
def split(
addrinfo: List[Tuple],
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
"""Partition the ``addrinfo`` list by address family.
Returns two lists. The first list contains the first entry from
``addrinfo`` and all others with the same family, and the
second list contains all other addresses (normally one list will
be AF_INET and the other AF_INET6, although non-standard resolvers
may return additional families).
"""
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr in addrinfo:
if af == primary_af:
primary.append((af, addr))
else:
secondary.append((af, addr))
return primary, secondary | [
75,
97
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
@staticmethod
def split(
addrinfo: List[Tuple],
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
"""Partition the ``addrinfo`` list by address family.
Returns two lists. The first list contains the first entry from
``addrinfo`` and all others with the same family, and the
second list contains all other addresses (normally one list will
be AF_INET and the other AF_INET6, although non-standard resolvers
may return additional families).
"""
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr in addrinfo:
if af == primary_af:
primary.append((af, addr))
else:
secondary.append((af, addr))
return primary, secondary | true | 2 |
751 | tornado | tornado.tcpclient | _Connector | start | def start(
self,
timeout: float = _INITIAL_CONNECT_TIMEOUT,
connect_timeout: Optional[Union[float, datetime.timedelta]] = None,
) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]":
self.try_connect(iter(self.primary_addrs))
self.set_timeout(timeout)
if connect_timeout is not None:
self.set_connect_timeout(connect_timeout)
return self.future | [
99,
108
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def start(
self,
timeout: float = _INITIAL_CONNECT_TIMEOUT,
connect_timeout: Optional[Union[float, datetime.timedelta]] = None,
) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]":
self.try_connect(iter(self.primary_addrs))
self.set_timeout(timeout)
if connect_timeout is not None:
self.set_connect_timeout(connect_timeout)
return self.future | true | 2 |
752 | tornado | tornado.tcpclient | _Connector | try_connect | def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:
try:
af, addr = next(addrs)
except StopIteration:
# We've reached the end of our queue, but the other queue
# might still be working. Send a final error on the future
# only when both queues are finished.
if self.remaining == 0 and not self.future.done():
self.future.set_exception(
self.last_error or IOError("connection failed")
)
return
stream, future = self.connect(af, addr)
self.streams.add(stream)
future_add_done_callback(
future, functools.partial(self.on_connect_done, addrs, af, addr)
) | [
110,
124
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:
try:
af, addr = next(addrs)
except StopIteration:
# We've reached the end of our queue, but the other queue
# might still be working. Send a final error on the future
# only when both queues are finished.
if self.remaining == 0 and not self.future.done():
self.future.set_exception(
self.last_error or IOError("connection failed")
)
return
stream, future = self.connect(af, addr)
self.streams.add(stream)
future_add_done_callback(
future, functools.partial(self.on_connect_done, addrs, af, addr)
) | true | 2 |
753 | tornado | tornado.tcpclient | _Connector | on_connect_done | def on_connect_done(
self,
addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],
af: socket.AddressFamily,
addr: Tuple,
future: "Future[IOStream]",
) -> None:
self.remaining -= 1
try:
stream = future.result()
except Exception as e:
if self.future.done():
return
# Error: try again (but remember what happened so we have an
# error to raise in the end)
self.last_error = e
self.try_connect(addrs)
if self.timeout is not None:
# If the first attempt failed, don't wait for the
# timeout to try an address from the secondary queue.
self.io_loop.remove_timeout(self.timeout)
self.on_timeout()
return
self.clear_timeouts()
if self.future.done():
# This is a late arrival; just drop it.
stream.close()
else:
self.streams.discard(stream)
self.future.set_result((af, addr, stream))
self.close_streams() | [
128,
158
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def on_connect_done(
self,
addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],
af: socket.AddressFamily,
addr: Tuple,
future: "Future[IOStream]",
) -> None:
self.remaining -= 1
try:
stream = future.result()
except Exception as e:
if self.future.done():
return
# Error: try again (but remember what happened so we have an
# error to raise in the end)
self.last_error = e
self.try_connect(addrs)
if self.timeout is not None:
# If the first attempt failed, don't wait for the
# timeout to try an address from the secondary queue.
self.io_loop.remove_timeout(self.timeout)
self.on_timeout()
return
self.clear_timeouts()
if self.future.done():
# This is a late arrival; just drop it.
stream.close()
else:
self.streams.discard(stream)
self.future.set_result((af, addr, stream))
self.close_streams() | true | 2 |
754 | tornado | tornado.tcpclient | _Connector | set_timeout | def set_timeout(self, timeout: float) -> None:
self.timeout = self.io_loop.add_timeout(
self.io_loop.time() + timeout, self.on_timeout
) | [
160,
161
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def set_timeout(self, timeout: float) -> None:
self.timeout = self.io_loop.add_timeout(
self.io_loop.time() + timeout, self.on_timeout
) | false | 0 |
755 | tornado | tornado.tcpclient | _Connector | on_timeout | def on_timeout(self) -> None:
self.timeout = None
if not self.future.done():
self.try_connect(iter(self.secondary_addrs)) | [
165,
168
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def on_timeout(self) -> None:
self.timeout = None
if not self.future.done():
self.try_connect(iter(self.secondary_addrs)) | true | 2 |
756 | tornado | tornado.tcpclient | _Connector | clear_timeout | def clear_timeout(self) -> None:
if self.timeout is not None:
self.io_loop.remove_timeout(self.timeout) | [
170,
172
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def clear_timeout(self) -> None:
if self.timeout is not None:
self.io_loop.remove_timeout(self.timeout) | true | 2 |
757 | tornado | tornado.tcpclient | _Connector | set_connect_timeout | def set_connect_timeout(
self, connect_timeout: Union[float, datetime.timedelta]
) -> None:
self.connect_timeout = self.io_loop.add_timeout(
connect_timeout, self.on_connect_timeout
) | [
174,
177
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def set_connect_timeout(
self, connect_timeout: Union[float, datetime.timedelta]
) -> None:
self.connect_timeout = self.io_loop.add_timeout(
connect_timeout, self.on_connect_timeout
) | false | 0 |
758 | tornado | tornado.tcpclient | _Connector | on_connect_timeout | def on_connect_timeout(self) -> None:
if not self.future.done():
self.future.set_exception(TimeoutError())
self.close_streams() | [
181,
184
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def on_connect_timeout(self) -> None:
if not self.future.done():
self.future.set_exception(TimeoutError())
self.close_streams() | true | 2 |
759 | tornado | tornado.tcpclient | _Connector | clear_timeouts | def clear_timeouts(self) -> None:
if self.timeout is not None:
self.io_loop.remove_timeout(self.timeout)
if self.connect_timeout is not None:
self.io_loop.remove_timeout(self.connect_timeout) | [
186,
190
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def clear_timeouts(self) -> None:
if self.timeout is not None:
self.io_loop.remove_timeout(self.timeout)
if self.connect_timeout is not None:
self.io_loop.remove_timeout(self.connect_timeout) | true | 2 |
760 | tornado | tornado.tcpclient | _Connector | close_streams | def close_streams(self) -> None:
for stream in self.streams:
stream.close() | [
192,
194
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
def close_streams(self) -> None:
for stream in self.streams:
stream.close() | true | 2 |
761 | tornado | tornado.tcpclient | TCPClient | connect | async def connect(
self,
host: str,
port: int,
af: socket.AddressFamily = socket.AF_UNSPEC,
ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
max_buffer_size: Optional[int] = None,
source_ip: Optional[str] = None,
source_port: Optional[int] = None,
timeout: Optional[Union[float, datetime.timedelta]] = None,
) -> IOStream:
"""Connect to the given host and port.
Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
``ssl_options`` is not None).
Using the ``source_ip`` kwarg, one can specify the source
IP address to use when establishing the connection.
In case the user needs to resolve and
use a specific interface, it has to be handled outside
of Tornado as this depends very much on the platform.
Raises `TimeoutError` if the input future does not complete before
``timeout``, which may be specified in any form allowed by
`.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
relative to `.IOLoop.time`)
Similarly, when the user requires a certain source port, it can
be specified using the ``source_port`` arg.
.. versionchanged:: 4.5
Added the ``source_ip`` and ``source_port`` arguments.
.. versionchanged:: 5.0
Added the ``timeout`` argument.
"""
if timeout is not None:
if isinstance(timeout, numbers.Real):
timeout = IOLoop.current().time() + timeout
elif isinstance(timeout, datetime.timedelta):
timeout = IOLoop.current().time() + timeout.total_seconds()
else:
raise TypeError("Unsupported timeout %r" % timeout)
if timeout is not None:
addrinfo = await gen.with_timeout(
timeout, self.resolver.resolve(host, port, af)
)
else:
addrinfo = await self.resolver.resolve(host, port, af)
connector = _Connector(
addrinfo,
functools.partial(
self._create_stream,
max_buffer_size,
source_ip=source_ip,
source_port=source_port,
),
)
af, addr, stream = await connector.start(connect_timeout=timeout)
# TODO: For better performance we could cache the (af, addr)
# information here and re-use it on subsequent connections to
# the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
if ssl_options is not None:
if timeout is not None:
stream = await gen.with_timeout(
timeout,
stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
),
)
else:
stream = await stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
)
return stream | [
216,
290
] | false | [
"_INITIAL_CONNECT_TIMEOUT"
] | import functools
import socket
import numbers
import datetime
import ssl
from tornado.concurrent import Future, future_add_done_callback
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.netutil import Resolver
from tornado.gen import TimeoutError
from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional, Set
_INITIAL_CONNECT_TIMEOUT = 0.3
class _Connector(object):
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set()
class TCPClient(object):
def __init__(self, resolver: Optional[Resolver] = None) -> None:
if resolver is not None:
self.resolver = resolver
self._own_resolver = False
else:
self.resolver = Resolver()
self._own_resolver = True
async def connect(
self,
host: str,
port: int,
af: socket.AddressFamily = socket.AF_UNSPEC,
ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
max_buffer_size: Optional[int] = None,
source_ip: Optional[str] = None,
source_port: Optional[int] = None,
timeout: Optional[Union[float, datetime.timedelta]] = None,
) -> IOStream:
"""Connect to the given host and port.
Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
``ssl_options`` is not None).
Using the ``source_ip`` kwarg, one can specify the source
IP address to use when establishing the connection.
In case the user needs to resolve and
use a specific interface, it has to be handled outside
of Tornado as this depends very much on the platform.
Raises `TimeoutError` if the input future does not complete before
``timeout``, which may be specified in any form allowed by
`.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
relative to `.IOLoop.time`)
Similarly, when the user requires a certain source port, it can
be specified using the ``source_port`` arg.
.. versionchanged:: 4.5
Added the ``source_ip`` and ``source_port`` arguments.
.. versionchanged:: 5.0
Added the ``timeout`` argument.
"""
if timeout is not None:
if isinstance(timeout, numbers.Real):
timeout = IOLoop.current().time() + timeout
elif isinstance(timeout, datetime.timedelta):
timeout = IOLoop.current().time() + timeout.total_seconds()
else:
raise TypeError("Unsupported timeout %r" % timeout)
if timeout is not None:
addrinfo = await gen.with_timeout(
timeout, self.resolver.resolve(host, port, af)
)
else:
addrinfo = await self.resolver.resolve(host, port, af)
connector = _Connector(
addrinfo,
functools.partial(
self._create_stream,
max_buffer_size,
source_ip=source_ip,
source_port=source_port,
),
)
af, addr, stream = await connector.start(connect_timeout=timeout)
# TODO: For better performance we could cache the (af, addr)
# information here and re-use it on subsequent connections to
# the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
if ssl_options is not None:
if timeout is not None:
stream = await gen.with_timeout(
timeout,
stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
),
)
else:
stream = await stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
)
return stream | true | 2 |
762 | tornado | tornado.util | import_object | def import_object(name: str) -> Any:
"""Imports an object by name.
``import_object('x')`` is equivalent to ``import x``.
``import_object('x.y.z')`` is equivalent to ``from x.y import z``.
>>> import tornado.escape
>>> import_object('tornado.escape') is tornado.escape
True
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
True
>>> import_object('tornado') is tornado
True
>>> import_object('tornado.missing_module')
Traceback (most recent call last):
...
ImportError: No module named missing_module
"""
if name.count(".") == 0:
return __import__(name)
parts = name.split(".")
obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]])
try:
return getattr(obj, parts[-1])
except AttributeError:
raise ImportError("No module named %s" % parts[-1]) | [
130,
156
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
def import_object(name: str) -> Any:
"""Imports an object by name.
``import_object('x')`` is equivalent to ``import x``.
``import_object('x.y.z')`` is equivalent to ``from x.y import z``.
>>> import tornado.escape
>>> import_object('tornado.escape') is tornado.escape
True
>>> import_object('tornado.escape.utf8') is tornado.escape.utf8
True
>>> import_object('tornado') is tornado
True
>>> import_object('tornado.missing_module')
Traceback (most recent call last):
...
ImportError: No module named missing_module
"""
if name.count(".") == 0:
return __import__(name)
parts = name.split(".")
obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]])
try:
return getattr(obj, parts[-1])
except AttributeError:
raise ImportError("No module named %s" % parts[-1]) | true | 2 | |
763 | tornado | tornado.util | raise_exc_info | def raise_exc_info(
exc_info, # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]
):
# type: (...) -> typing.NoReturn
#
# This function's type annotation must use comments instead of
# real annotations because typing.NoReturn does not exist in
# python 3.5's typing module. The formatting is funky because this
# is apparently what flake8 wants.
try:
if exc_info[1] is not None:
raise exc_info[1].with_traceback(exc_info[2])
else:
raise TypeError("raise_exc_info called with no exception")
finally:
# Clear the traceback reference from our stack frame to
# minimize circular references that slow down GC.
exc_info = (None, None, None) | [
169,
186
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
def raise_exc_info(
exc_info, # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]]
):
# type: (...) -> typing.NoReturn
#
# This function's type annotation must use comments instead of
# real annotations because typing.NoReturn does not exist in
# python 3.5's typing module. The formatting is funky because this
# is apparently what flake8 wants.
try:
if exc_info[1] is not None:
raise exc_info[1].with_traceback(exc_info[2])
else:
raise TypeError("raise_exc_info called with no exception")
finally:
# Clear the traceback reference from our stack frame to
# minimize circular references that slow down GC.
exc_info = (None, None, None) | true | 2 | |
764 | tornado | tornado.util | errno_from_exception | def errno_from_exception(e: BaseException) -> Optional[int]:
"""Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instantiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
errno.
"""
if hasattr(e, "errno"):
return e.errno # type: ignore
elif e.args:
return e.args[0]
else:
return None | [
189,
204
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
def errno_from_exception(e: BaseException) -> Optional[int]:
"""Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instantiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
errno.
"""
if hasattr(e, "errno"):
return e.errno # type: ignore
elif e.args:
return e.args[0]
else:
return None | true | 2 | |
765 | tornado | tornado.util | ObjectDict | __getattr__ | def __getattr__(self, name: str) -> Any:
try:
return self[name]
except KeyError:
raise AttributeError(name) | [
79,
83
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
class ObjectDict(Dict[str, Any]):
def __getattr__(self, name: str) -> Any:
try:
return self[name]
except KeyError:
raise AttributeError(name) | false | 0 |
766 | tornado | tornado.util | Configurable | __new__ | def __new__(cls, *args: Any, **kwargs: Any) -> Any:
base = cls.configurable_base()
init_kwargs = {} # type: Dict[str, Any]
if cls is base:
impl = cls.configured_class()
if base.__impl_kwargs:
init_kwargs.update(base.__impl_kwargs)
else:
impl = cls
init_kwargs.update(kwargs)
if impl.configurable_base() is not base:
# The impl class is itself configurable, so recurse.
return impl(*args, **init_kwargs)
instance = super(Configurable, cls).__new__(impl)
# initialize vs __init__ chosen for compatibility with AsyncHTTPClient
# singleton magic. If we get rid of that we can switch to __init__
# here too.
instance.initialize(*args, **init_kwargs)
return instance | [
270,
288
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
class Configurable(object):
__impl_class = None
__impl_kwargs = None
initialize = _initialize
def __new__(cls, *args: Any, **kwargs: Any) -> Any:
base = cls.configurable_base()
init_kwargs = {} # type: Dict[str, Any]
if cls is base:
impl = cls.configured_class()
if base.__impl_kwargs:
init_kwargs.update(base.__impl_kwargs)
else:
impl = cls
init_kwargs.update(kwargs)
if impl.configurable_base() is not base:
# The impl class is itself configurable, so recurse.
return impl(*args, **init_kwargs)
instance = super(Configurable, cls).__new__(impl)
# initialize vs __init__ chosen for compatibility with AsyncHTTPClient
# singleton magic. If we get rid of that we can switch to __init__
# here too.
instance.initialize(*args, **init_kwargs)
return instance | true | 2 |
767 | tornado | tornado.util | ArgReplacer | __init__ | def __init__(self, func: Callable, name: str) -> None:
self.name = name
try:
self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]
except ValueError:
# Not a positional parameter
self.arg_pos = None | [
375,
381
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
class ArgReplacer(object):
def __init__(self, func: Callable, name: str) -> None:
self.name = name
try:
self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]
except ValueError:
# Not a positional parameter
self.arg_pos = None | false | 0 |
768 | tornado | tornado.util | ArgReplacer | get_old_value | def get_old_value(
self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None
) -> Any:
"""Returns the old value of the named argument without replacing it.
Returns ``default`` if the argument is not present.
"""
if self.arg_pos is not None and len(args) > self.arg_pos:
return args[self.arg_pos]
else:
return kwargs.get(self.name, default) | [
398,
408
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
class ArgReplacer(object):
def __init__(self, func: Callable, name: str) -> None:
self.name = name
try:
self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]
except ValueError:
# Not a positional parameter
self.arg_pos = None
def get_old_value(
self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None
) -> Any:
"""Returns the old value of the named argument without replacing it.
Returns ``default`` if the argument is not present.
"""
if self.arg_pos is not None and len(args) > self.arg_pos:
return args[self.arg_pos]
else:
return kwargs.get(self.name, default) | true | 2 |
769 | tornado | tornado.util | ArgReplacer | replace | def replace(
self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any]
) -> Tuple[Any, Sequence[Any], Dict[str, Any]]:
"""Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be mutated.
If the named argument was not found, ``new_value`` will be added
to ``kwargs`` and None will be returned as ``old_value``.
"""
if self.arg_pos is not None and len(args) > self.arg_pos:
# The arg to replace is passed positionally
old_value = args[self.arg_pos]
args = list(args) # *args is normally a tuple
args[self.arg_pos] = new_value
else:
# The arg to replace is either omitted or passed by keyword.
old_value = kwargs.get(self.name)
kwargs[self.name] = new_value
return old_value, args, kwargs | [
410,
431
] | false | [
"bytes_type",
"unicode_type",
"basestring_type",
"_alphanum",
"_re_unescape_pattern"
] | import array
import atexit
from inspect import getfullargspec
import os
import re
import typing
import zlib
from typing import (
Any,
Optional,
Dict,
Mapping,
List,
Tuple,
Match,
Callable,
Type,
Sequence,
)
bytes_type = bytes
unicode_type = str
basestring_type = str
_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
_re_unescape_pattern = re.compile(r"\\(.)", re.DOTALL)
class ArgReplacer(object):
def __init__(self, func: Callable, name: str) -> None:
self.name = name
try:
self.arg_pos = self._getargnames(func).index(name) # type: Optional[int]
except ValueError:
# Not a positional parameter
self.arg_pos = None
def replace(
self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any]
) -> Tuple[Any, Sequence[Any], Dict[str, Any]]:
"""Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be mutated.
If the named argument was not found, ``new_value`` will be added
to ``kwargs`` and None will be returned as ``old_value``.
"""
if self.arg_pos is not None and len(args) > self.arg_pos:
# The arg to replace is passed positionally
old_value = args[self.arg_pos]
args = list(args) # *args is normally a tuple
args[self.arg_pos] = new_value
else:
# The arg to replace is either omitted or passed by keyword.
old_value = kwargs.get(self.name)
kwargs[self.name] = new_value
return old_value, args, kwargs | true | 2 |
770 | tqdm | tqdm._tqdm_pandas | tqdm_pandas | def tqdm_pandas(tclass, **tqdm_kwargs):
"""
Registers the given `tqdm` instance with
`pandas.core.groupby.DataFrameGroupBy.progress_apply`.
"""
from tqdm import TqdmDeprecationWarning
if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(
'tqdm_')): # delayed adapter case
TqdmDeprecationWarning(
"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.",
fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))
tclass.pandas(**tqdm_kwargs)
else:
TqdmDeprecationWarning(
"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.",
fp_write=getattr(tclass.fp, 'write', sys.stderr.write))
type(tclass).pandas(deprecated_t=tclass) | [
6,
23
] | false | [
"__author__",
"__all__"
] | import sys
__author__ = "github.com/casperdcl"
__all__ = ['tqdm_pandas']
def tqdm_pandas(tclass, **tqdm_kwargs):
"""
Registers the given `tqdm` instance with
`pandas.core.groupby.DataFrameGroupBy.progress_apply`.
"""
from tqdm import TqdmDeprecationWarning
if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(
'tqdm_')): # delayed adapter case
TqdmDeprecationWarning(
"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.",
fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))
tclass.pandas(**tqdm_kwargs)
else:
TqdmDeprecationWarning(
"Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.",
fp_write=getattr(tclass.fp, 'write', sys.stderr.write))
type(tclass).pandas(deprecated_t=tclass) | true | 2 | |
771 | tqdm | tqdm.contrib.itertools | product | def product(*iterables, **tqdm_kwargs):
"""
Equivalent of `itertools.product`.
Parameters
----------
tqdm_class : [default: tqdm.auto.tqdm].
"""
kwargs = tqdm_kwargs.copy()
tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
try:
lens = list(map(len, iterables))
except TypeError:
total = None
else:
total = 1
for i in lens:
total *= i
kwargs.setdefault("total", total)
with tqdm_class(**kwargs) as t:
for i in itertools.product(*iterables):
yield i
t.update() | [
13,
35
] | false | [
"__author__",
"__all__"
] | import itertools
from ..auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['product']
def product(*iterables, **tqdm_kwargs):
"""
Equivalent of `itertools.product`.
Parameters
----------
tqdm_class : [default: tqdm.auto.tqdm].
"""
kwargs = tqdm_kwargs.copy()
tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
try:
lens = list(map(len, iterables))
except TypeError:
total = None
else:
total = 1
for i in lens:
total *= i
kwargs.setdefault("total", total)
with tqdm_class(**kwargs) as t:
for i in itertools.product(*iterables):
yield i
t.update() | true | 2 | |
772 | tqdm | tqdm.contrib.logging | _TqdmLoggingHandler | emit | def emit(self, record):
try:
msg = self.format(record)
self.tqdm_class.write(msg, file=self.stream)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except: # noqa pylint: disable=bare-except
self.handleError(record) | [
25,
33
] | false | [] | import logging
import sys
from contextlib import contextmanager
from ..std import tqdm as std_tqdm
class _TqdmLoggingHandler(logging.StreamHandler):
def __init__(
self,
tqdm_class=std_tqdm # type: Type[std_tqdm]
):
super(_TqdmLoggingHandler, self).__init__()
self.tqdm_class = tqdm_class
def emit(self, record):
try:
msg = self.format(record)
self.tqdm_class.write(msg, file=self.stream)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except: # noqa pylint: disable=bare-except
self.handleError(record) | false | 0 |
773 | tqdm | tqdm.contrib.telegram | TelegramIO | write | def write(self, s):
"""Replaces internal `message_id`'s text with `s`."""
if not s:
s = "..."
s = s.replace('\r', '').strip()
if s == self.text:
return # avoid duplicate message Bot error
message_id = self.message_id
if message_id is None:
return
self.text = s
try:
future = self.submit(
self.session.post, self.API + '%s/editMessageText' % self.token,
data={'text': '`' + s + '`', 'chat_id': self.chat_id,
'message_id': message_id, 'parse_mode': 'MarkdownV2'})
except Exception as e:
tqdm_auto.write(str(e))
else:
return future | [
58,
77
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class TelegramIO(MonoWorker):
API = 'https://api.telegram.org/bot'
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super(TelegramIO, self).__init__()
self.token = token
self.chat_id = chat_id
self.session = Session()
self.text = self.__class__.__name__
self.message_id
def write(self, s):
"""Replaces internal `message_id`'s text with `s`."""
if not s:
s = "..."
s = s.replace('\r', '').strip()
if s == self.text:
return # avoid duplicate message Bot error
message_id = self.message_id
if message_id is None:
return
self.text = s
try:
future = self.submit(
self.session.post, self.API + '%s/editMessageText' % self.token,
data={'text': '`' + s + '`', 'chat_id': self.chat_id,
'message_id': message_id, 'parse_mode': 'MarkdownV2'})
except Exception as e:
tqdm_auto.write(str(e))
else:
return future | true | 2 |
774 | tqdm | tqdm.contrib.telegram | TelegramIO | delete | def delete(self):
"""Deletes internal `message_id`."""
try:
future = self.submit(
self.session.post, self.API + '%s/deleteMessage' % self.token,
data={'chat_id': self.chat_id, 'message_id': self.message_id})
except Exception as e:
tqdm_auto.write(str(e))
else:
return future | [
79,
88
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class TelegramIO(MonoWorker):
API = 'https://api.telegram.org/bot'
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super(TelegramIO, self).__init__()
self.token = token
self.chat_id = chat_id
self.session = Session()
self.text = self.__class__.__name__
self.message_id
def delete(self):
"""Deletes internal `message_id`."""
try:
future = self.submit(
self.session.post, self.API + '%s/deleteMessage' % self.token,
data={'chat_id': self.chat_id, 'message_id': self.message_id})
except Exception as e:
tqdm_auto.write(str(e))
else:
return future | false | 0 |
775 | tqdm | tqdm.contrib.telegram | tqdm_telegram | __init__ | def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs) | [
107,
123
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class TelegramIO(MonoWorker):
API = 'https://api.telegram.org/bot'
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super(TelegramIO, self).__init__()
self.token = token
self.chat_id = chat_id
self.session = Session()
self.text = self.__class__.__name__
self.message_id
class tqdm_telegram(tqdm_auto):
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs) | true | 2 |
776 | tqdm | tqdm.contrib.telegram | tqdm_telegram | display | def display(self, **kwargs):
super(tqdm_telegram, self).display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
'<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
else:
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.tgio.write(self.format_meter(**fmt)) | [
125,
133
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class tqdm_telegram(tqdm_auto):
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs)
def display(self, **kwargs):
super(tqdm_telegram, self).display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
'<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
else:
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.tgio.write(self.format_meter(**fmt)) | true | 2 |
777 | tqdm | tqdm.contrib.telegram | tqdm_telegram | clear | def clear(self, *args, **kwargs):
super(tqdm_telegram, self).clear(*args, **kwargs)
if not self.disable:
self.tgio.write("") | [
135,
138
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class tqdm_telegram(tqdm_auto):
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs)
def clear(self, *args, **kwargs):
super(tqdm_telegram, self).clear(*args, **kwargs)
if not self.disable:
self.tgio.write("") | true | 2 |
778 | tqdm | tqdm.contrib.telegram | tqdm_telegram | close | def close(self):
if self.disable:
return
super(tqdm_telegram, self).close()
if not (self.leave or (self.leave is None and self.pos == 0)):
self.tgio.delete() | [
140,
145
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from os import getenv
from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from ..utils import _range
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
tqdm = tqdm_telegram
trange = ttgrange
class tqdm_telegram(tqdm_auto):
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs)
def close(self):
if self.disable:
return
super(tqdm_telegram, self).close()
if not (self.leave or (self.leave is None and self.pos == 0)):
self.tgio.delete() | true | 2 |
779 | tqdm | tqdm.contrib.utils_worker | MonoWorker | submit | def submit(self, func, *args, **kwargs):
"""`func(*args, **kwargs)` may replace currently waiting task."""
futures = self.futures
if len(futures) == futures.maxlen:
running = futures.popleft()
if not running.done():
if len(futures): # clear waiting
waiting = futures.pop()
waiting.cancel()
futures.appendleft(running) # re-insert running
try:
waiting = self.pool.submit(func, *args, **kwargs)
except Exception as e:
tqdm_auto.write(str(e))
else:
futures.append(waiting)
return waiting | [
23,
39
] | false | [
"__author__",
"__all__"
] | from collections import deque
from concurrent.futures import ThreadPoolExecutor
from ..auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['MonoWorker']
class MonoWorker(object):
def __init__(self):
self.pool = ThreadPoolExecutor(max_workers=1)
self.futures = deque([], 2)
def submit(self, func, *args, **kwargs):
"""`func(*args, **kwargs)` may replace currently waiting task."""
futures = self.futures
if len(futures) == futures.maxlen:
running = futures.popleft()
if not running.done():
if len(futures): # clear waiting
waiting = futures.pop()
waiting.cancel()
futures.appendleft(running) # re-insert running
try:
waiting = self.pool.submit(func, *args, **kwargs)
except Exception as e:
tqdm_auto.write(str(e))
else:
futures.append(waiting)
return waiting | true | 2 |
780 | tqdm | tqdm.gui | tqdm_gui | __init__ | def __init__(self, *args, **kwargs):
from collections import deque
import matplotlib as mpl
import matplotlib.pyplot as plt
kwargs = kwargs.copy()
kwargs['gui'] = True
colour = kwargs.pop('colour', 'g')
super(tqdm_gui, self).__init__(*args, **kwargs)
if self.disable:
return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
self.mpl = mpl
self.plt = plt
# Remember if external environment uses toolbars
self.toolbar = self.mpl.rcParams['toolbar']
self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5)
self.fig, ax = plt.subplots(figsize=(9, 2.2))
# self.fig.subplots_adjust(bottom=0.2)
total = self.__len__() # avoids TypeError on None #971
if total is not None:
self.xdata = []
self.ydata = []
self.zdata = []
else:
self.xdata = deque([])
self.ydata = deque([])
self.zdata = deque([])
self.line1, = ax.plot(self.xdata, self.ydata, color='b')
self.line2, = ax.plot(self.xdata, self.zdata, color='k')
ax.set_ylim(0, 0.001)
if total is not None:
ax.set_xlim(0, 100)
ax.set_xlabel("percent")
self.fig.legend((self.line1, self.line2), ("cur", "est"),
loc='center right')
# progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
else:
# ax.set_xlim(-60, 0)
ax.set_xlim(0, 60)
ax.invert_xaxis()
ax.set_xlabel("seconds")
ax.legend(("cur", "est"), loc='lower left')
ax.grid()
# ax.set_xlabel('seconds')
ax.set_ylabel((self.unit if self.unit else "it") + "/s")
if self.unit_scale:
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive
self.wasion = plt.isinteractive()
plt.ion()
self.ax = ax | [
28,
87
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
from warnings import warn
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl", "lrq3000"]}
__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
tqdm = tqdm_gui
trange = tgrange
class tqdm_gui(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
from collections import deque
import matplotlib as mpl
import matplotlib.pyplot as plt
kwargs = kwargs.copy()
kwargs['gui'] = True
colour = kwargs.pop('colour', 'g')
super(tqdm_gui, self).__init__(*args, **kwargs)
if self.disable:
return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
self.mpl = mpl
self.plt = plt
# Remember if external environment uses toolbars
self.toolbar = self.mpl.rcParams['toolbar']
self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5)
self.fig, ax = plt.subplots(figsize=(9, 2.2))
# self.fig.subplots_adjust(bottom=0.2)
total = self.__len__() # avoids TypeError on None #971
if total is not None:
self.xdata = []
self.ydata = []
self.zdata = []
else:
self.xdata = deque([])
self.ydata = deque([])
self.zdata = deque([])
self.line1, = ax.plot(self.xdata, self.ydata, color='b')
self.line2, = ax.plot(self.xdata, self.zdata, color='k')
ax.set_ylim(0, 0.001)
if total is not None:
ax.set_xlim(0, 100)
ax.set_xlabel("percent")
self.fig.legend((self.line1, self.line2), ("cur", "est"),
loc='center right')
# progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
else:
# ax.set_xlim(-60, 0)
ax.set_xlim(0, 60)
ax.invert_xaxis()
ax.set_xlabel("seconds")
ax.legend(("cur", "est"), loc='lower left')
ax.grid()
# ax.set_xlabel('seconds')
ax.set_ylabel((self.unit if self.unit else "it") + "/s")
if self.unit_scale:
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive
self.wasion = plt.isinteractive()
plt.ion()
self.ax = ax | false | 0 |
781 | tqdm | tqdm.gui | tqdm_gui | close | def close(self):
if self.disable:
return
self.disable = True
with self.get_lock():
self._instances.remove(self)
# Restore toolbars
self.mpl.rcParams['toolbar'] = self.toolbar
# Return to non-interactive mode
if not self.wasion:
self.plt.ioff()
if self.leave:
self.display()
else:
self.plt.close(self.fig) | [
89,
106
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
from warnings import warn
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl", "lrq3000"]}
__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
tqdm = tqdm_gui
trange = tgrange
class tqdm_gui(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
from collections import deque
import matplotlib as mpl
import matplotlib.pyplot as plt
kwargs = kwargs.copy()
kwargs['gui'] = True
colour = kwargs.pop('colour', 'g')
super(tqdm_gui, self).__init__(*args, **kwargs)
if self.disable:
return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
self.mpl = mpl
self.plt = plt
# Remember if external environment uses toolbars
self.toolbar = self.mpl.rcParams['toolbar']
self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5)
self.fig, ax = plt.subplots(figsize=(9, 2.2))
# self.fig.subplots_adjust(bottom=0.2)
total = self.__len__() # avoids TypeError on None #971
if total is not None:
self.xdata = []
self.ydata = []
self.zdata = []
else:
self.xdata = deque([])
self.ydata = deque([])
self.zdata = deque([])
self.line1, = ax.plot(self.xdata, self.ydata, color='b')
self.line2, = ax.plot(self.xdata, self.zdata, color='k')
ax.set_ylim(0, 0.001)
if total is not None:
ax.set_xlim(0, 100)
ax.set_xlabel("percent")
self.fig.legend((self.line1, self.line2), ("cur", "est"),
loc='center right')
# progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
else:
# ax.set_xlim(-60, 0)
ax.set_xlim(0, 60)
ax.invert_xaxis()
ax.set_xlabel("seconds")
ax.legend(("cur", "est"), loc='lower left')
ax.grid()
# ax.set_xlabel('seconds')
ax.set_ylabel((self.unit if self.unit else "it") + "/s")
if self.unit_scale:
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive
self.wasion = plt.isinteractive()
plt.ion()
self.ax = ax
def close(self):
if self.disable:
return
self.disable = True
with self.get_lock():
self._instances.remove(self)
# Restore toolbars
self.mpl.rcParams['toolbar'] = self.toolbar
# Return to non-interactive mode
if not self.wasion:
self.plt.ioff()
if self.leave:
self.display()
else:
self.plt.close(self.fig) | false | 0 |
782 | tqdm | tqdm.gui | tqdm_gui | clear | def clear(self, *_, **__):
pass | [
108,
109
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
from warnings import warn
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl", "lrq3000"]}
__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
tqdm = tqdm_gui
trange = tgrange
class tqdm_gui(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
from collections import deque
import matplotlib as mpl
import matplotlib.pyplot as plt
kwargs = kwargs.copy()
kwargs['gui'] = True
colour = kwargs.pop('colour', 'g')
super(tqdm_gui, self).__init__(*args, **kwargs)
if self.disable:
return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
self.mpl = mpl
self.plt = plt
# Remember if external environment uses toolbars
self.toolbar = self.mpl.rcParams['toolbar']
self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5)
self.fig, ax = plt.subplots(figsize=(9, 2.2))
# self.fig.subplots_adjust(bottom=0.2)
total = self.__len__() # avoids TypeError on None #971
if total is not None:
self.xdata = []
self.ydata = []
self.zdata = []
else:
self.xdata = deque([])
self.ydata = deque([])
self.zdata = deque([])
self.line1, = ax.plot(self.xdata, self.ydata, color='b')
self.line2, = ax.plot(self.xdata, self.zdata, color='k')
ax.set_ylim(0, 0.001)
if total is not None:
ax.set_xlim(0, 100)
ax.set_xlabel("percent")
self.fig.legend((self.line1, self.line2), ("cur", "est"),
loc='center right')
# progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
else:
# ax.set_xlim(-60, 0)
ax.set_xlim(0, 60)
ax.invert_xaxis()
ax.set_xlabel("seconds")
ax.legend(("cur", "est"), loc='lower left')
ax.grid()
# ax.set_xlabel('seconds')
ax.set_ylabel((self.unit if self.unit else "it") + "/s")
if self.unit_scale:
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive
self.wasion = plt.isinteractive()
plt.ion()
self.ax = ax
def clear(self, *_, **__):
pass | false | 0 |
783 | tqdm | tqdm.gui | tqdm_gui | display | def display(self, *_, **__):
n = self.n
cur_t = self._time()
elapsed = cur_t - self.start_t
delta_it = n - self.last_print_n
delta_t = cur_t - self.last_print_t
# Inline due to multiple calls
total = self.total
xdata = self.xdata
ydata = self.ydata
zdata = self.zdata
ax = self.ax
line1 = self.line1
line2 = self.line2
# instantaneous rate
y = delta_it / delta_t
# overall rate
z = n / elapsed
# update line data
xdata.append(n * 100.0 / total if total else cur_t)
ydata.append(y)
zdata.append(z)
# Discard old values
# xmin, xmax = ax.get_xlim()
# if (not total) and elapsed > xmin * 1.1:
if (not total) and elapsed > 66:
xdata.popleft()
ydata.popleft()
zdata.popleft()
ymin, ymax = ax.get_ylim()
if y > ymax or z > ymax:
ymax = 1.1 * y
ax.set_ylim(ymin, ymax)
ax.figure.canvas.draw()
if total:
line1.set_data(xdata, ydata)
line2.set_data(xdata, zdata)
try:
poly_lims = self.hspan.get_xy()
except AttributeError:
self.hspan = self.plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g')
poly_lims = self.hspan.get_xy()
poly_lims[0, 1] = ymin
poly_lims[1, 1] = ymax
poly_lims[2] = [n / total, ymax]
poly_lims[3] = [poly_lims[2, 0], ymin]
if len(poly_lims) > 4:
poly_lims[4, 1] = ymin
self.hspan.set_xy(poly_lims)
else:
t_ago = [cur_t - i for i in xdata]
line1.set_data(t_ago, ydata)
line2.set_data(t_ago, zdata)
d = self.format_dict
# remove {bar}
d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
"{bar}", "<bar/>")
msg = self.format_meter(**d)
if '<bar/>' in msg:
msg = "".join(re.split(r'\|?<bar/>\|?', msg, 1))
ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11)
self.plt.pause(1e-9) | [
111,
177
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
from warnings import warn
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl", "lrq3000"]}
__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
tqdm = tqdm_gui
trange = tgrange
class tqdm_gui(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
from collections import deque
import matplotlib as mpl
import matplotlib.pyplot as plt
kwargs = kwargs.copy()
kwargs['gui'] = True
colour = kwargs.pop('colour', 'g')
super(tqdm_gui, self).__init__(*args, **kwargs)
if self.disable:
return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
self.mpl = mpl
self.plt = plt
# Remember if external environment uses toolbars
self.toolbar = self.mpl.rcParams['toolbar']
self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5)
self.fig, ax = plt.subplots(figsize=(9, 2.2))
# self.fig.subplots_adjust(bottom=0.2)
total = self.__len__() # avoids TypeError on None #971
if total is not None:
self.xdata = []
self.ydata = []
self.zdata = []
else:
self.xdata = deque([])
self.ydata = deque([])
self.zdata = deque([])
self.line1, = ax.plot(self.xdata, self.ydata, color='b')
self.line2, = ax.plot(self.xdata, self.zdata, color='k')
ax.set_ylim(0, 0.001)
if total is not None:
ax.set_xlim(0, 100)
ax.set_xlabel("percent")
self.fig.legend((self.line1, self.line2), ("cur", "est"),
loc='center right')
# progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
else:
# ax.set_xlim(-60, 0)
ax.set_xlim(0, 60)
ax.invert_xaxis()
ax.set_xlabel("seconds")
ax.legend(("cur", "est"), loc='lower left')
ax.grid()
# ax.set_xlabel('seconds')
ax.set_ylabel((self.unit if self.unit else "it") + "/s")
if self.unit_scale:
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive
self.wasion = plt.isinteractive()
plt.ion()
self.ax = ax
def display(self, *_, **__):
n = self.n
cur_t = self._time()
elapsed = cur_t - self.start_t
delta_it = n - self.last_print_n
delta_t = cur_t - self.last_print_t
# Inline due to multiple calls
total = self.total
xdata = self.xdata
ydata = self.ydata
zdata = self.zdata
ax = self.ax
line1 = self.line1
line2 = self.line2
# instantaneous rate
y = delta_it / delta_t
# overall rate
z = n / elapsed
# update line data
xdata.append(n * 100.0 / total if total else cur_t)
ydata.append(y)
zdata.append(z)
# Discard old values
# xmin, xmax = ax.get_xlim()
# if (not total) and elapsed > xmin * 1.1:
if (not total) and elapsed > 66:
xdata.popleft()
ydata.popleft()
zdata.popleft()
ymin, ymax = ax.get_ylim()
if y > ymax or z > ymax:
ymax = 1.1 * y
ax.set_ylim(ymin, ymax)
ax.figure.canvas.draw()
if total:
line1.set_data(xdata, ydata)
line2.set_data(xdata, zdata)
try:
poly_lims = self.hspan.get_xy()
except AttributeError:
self.hspan = self.plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g')
poly_lims = self.hspan.get_xy()
poly_lims[0, 1] = ymin
poly_lims[1, 1] = ymax
poly_lims[2] = [n / total, ymax]
poly_lims[3] = [poly_lims[2, 0], ymin]
if len(poly_lims) > 4:
poly_lims[4, 1] = ymin
self.hspan.set_xy(poly_lims)
else:
t_ago = [cur_t - i for i in xdata]
line1.set_data(t_ago, ydata)
line2.set_data(t_ago, zdata)
d = self.format_dict
# remove {bar}
d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
"{bar}", "<bar/>")
msg = self.format_meter(**d)
if '<bar/>' in msg:
msg = "".join(re.split(r'\|?<bar/>\|?', msg, 1))
ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11)
self.plt.pause(1e-9) | false | 0 |
784 | tqdm | tqdm.notebook | TqdmHBox | __repr__ | def __repr__(self, pretty=False):
pbar = getattr(self, 'pbar', None)
if pbar is None:
return super(TqdmHBox, self).__repr__()
return pbar.format_meter(**self._repr_json_(pretty)) | [
86,
90
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class TqdmHBox(HBox):
def __repr__(self, pretty=False):
pbar = getattr(self, 'pbar', None)
if pbar is None:
return super(TqdmHBox, self).__repr__()
return pbar.format_meter(**self._repr_json_(pretty)) | true | 2 |
785 | tqdm | tqdm.notebook | tqdm_notebook | status_printer | @staticmethod
def status_printer(_, total=None, desc=None, ncols=None):
"""
Manage the printing of an IPython/Jupyter Notebook progress bar widget.
"""
# Fallback to text bar if there's no total
# DEPRECATED: replaced with an 'info' style bar
# if not total:
# return super(tqdm_notebook, tqdm_notebook).status_printer(file)
# fp = file
# Prepare IPython progress bar
if IProgress is None: # #187 #451 #558 #872
raise ImportError(
"IProgress not found. Please update jupyter and ipywidgets."
" See https://ipywidgets.readthedocs.io/en/stable"
"/user_install.html")
if total:
pbar = IProgress(min=0, max=total)
else: # No total? Show info style bar with no progress tqdm status
pbar = IProgress(min=0, max=1)
pbar.value = 1
pbar.bar_style = 'info'
if ncols is None:
pbar.layout.width = "20px"
ltext = HTML()
rtext = HTML()
if desc:
ltext.value = desc
container = TqdmHBox(children=[ltext, pbar, rtext])
# Prepare layout
if ncols is not None: # use default style of ipywidgets
# ncols could be 100, "100px", "100%"
ncols = str(ncols) # ipywidgets only accepts string
try:
if int(ncols) > 0: # isnumeric and positive
ncols += 'px'
except ValueError:
pass
pbar.layout.flex = '2'
container.layout.width = ncols
container.layout.display = 'inline-flex'
container.layout.flex_flow = 'row wrap'
return container | [
101,
146
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
@staticmethod
def status_printer(_, total=None, desc=None, ncols=None):
"""
Manage the printing of an IPython/Jupyter Notebook progress bar widget.
"""
# Fallback to text bar if there's no total
# DEPRECATED: replaced with an 'info' style bar
# if not total:
# return super(tqdm_notebook, tqdm_notebook).status_printer(file)
# fp = file
# Prepare IPython progress bar
if IProgress is None: # #187 #451 #558 #872
raise ImportError(
"IProgress not found. Please update jupyter and ipywidgets."
" See https://ipywidgets.readthedocs.io/en/stable"
"/user_install.html")
if total:
pbar = IProgress(min=0, max=total)
else: # No total? Show info style bar with no progress tqdm status
pbar = IProgress(min=0, max=1)
pbar.value = 1
pbar.bar_style = 'info'
if ncols is None:
pbar.layout.width = "20px"
ltext = HTML()
rtext = HTML()
if desc:
ltext.value = desc
container = TqdmHBox(children=[ltext, pbar, rtext])
# Prepare layout
if ncols is not None: # use default style of ipywidgets
# ncols could be 100, "100px", "100%"
ncols = str(ncols) # ipywidgets only accepts string
try:
if int(ncols) > 0: # isnumeric and positive
ncols += 'px'
except ValueError:
pass
pbar.layout.flex = '2'
container.layout.width = ncols
container.layout.display = 'inline-flex'
container.layout.flex_flow = 'row wrap'
return container | true | 2 |
786 | tqdm | tqdm.notebook | tqdm_notebook | display | def display(self, msg=None, pos=None,
# additional signals
close=False, bar_style=None, check_delay=True):
# Note: contrary to native tqdm, msg='' does NOT clear bar
# goal is to keep all infos if error happens so user knows
# at which iteration the loop failed.
# Clear previous output (really necessary?)
# clear_output(wait=1)
if not msg and not close:
d = self.format_dict
# remove {bar}
d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
"{bar}", "<bar/>")
msg = self.format_meter(**d)
ltext, pbar, rtext = self.container.children
pbar.value = self.n
if msg:
# html escape special characters (like '&')
if '<bar/>' in msg:
left, right = map(escape, re.split(r'\|?<bar/>\|?', msg, 1))
else:
left, right = '', escape(msg)
# Update description
ltext.value = left
# never clear the bar (signal: msg='')
if right:
rtext.value = right
# Change bar style
if bar_style:
# Hack-ish way to avoid the danger bar_style being overridden by
# success because the bar gets closed after the error...
if pbar.bar_style != 'danger' or bar_style != 'success':
pbar.bar_style = bar_style
# Special signal to close the bar
if close and pbar.bar_style != 'danger': # hide only if no error
try:
self.container.close()
except AttributeError:
self.container.visible = False
if check_delay and self.delay > 0 and not self.displayed:
display(self.container)
self.displayed = True | [
148,
197
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def display(self, msg=None, pos=None,
# additional signals
close=False, bar_style=None, check_delay=True):
# Note: contrary to native tqdm, msg='' does NOT clear bar
# goal is to keep all infos if error happens so user knows
# at which iteration the loop failed.
# Clear previous output (really necessary?)
# clear_output(wait=1)
if not msg and not close:
d = self.format_dict
# remove {bar}
d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
"{bar}", "<bar/>")
msg = self.format_meter(**d)
ltext, pbar, rtext = self.container.children
pbar.value = self.n
if msg:
# html escape special characters (like '&')
if '<bar/>' in msg:
left, right = map(escape, re.split(r'\|?<bar/>\|?', msg, 1))
else:
left, right = '', escape(msg)
# Update description
ltext.value = left
# never clear the bar (signal: msg='')
if right:
rtext.value = right
# Change bar style
if bar_style:
# Hack-ish way to avoid the danger bar_style being overridden by
# success because the bar gets closed after the error...
if pbar.bar_style != 'danger' or bar_style != 'success':
pbar.bar_style = bar_style
# Special signal to close the bar
if close and pbar.bar_style != 'danger': # hide only if no error
try:
self.container.close()
except AttributeError:
self.container.visible = False
if check_delay and self.delay > 0 and not self.displayed:
display(self.container)
self.displayed = True | true | 2 |
787 | tqdm | tqdm.notebook | tqdm_notebook | __init__ | def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False) | [
209,
252
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False) | true | 2 |
788 | tqdm | tqdm.notebook | tqdm_notebook | __iter__ | def __iter__(self):
try:
for obj in super(tqdm_notebook, self).__iter__():
# return super(tqdm...) will not catch exception
yield obj
# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
except: # NOQA
self.disp(bar_style='danger')
raise
# NB: don't `finally: close()`
# since this could be a shared bar which the user will `reset()` | [
254,
262
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def __iter__(self):
try:
for obj in super(tqdm_notebook, self).__iter__():
# return super(tqdm...) will not catch exception
yield obj
# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
except: # NOQA
self.disp(bar_style='danger')
raise
# NB: don't `finally: close()`
# since this could be a shared bar which the user will `reset()` | true | 2 |
789 | tqdm | tqdm.notebook | tqdm_notebook | update | def update(self, n=1):
try:
return super(tqdm_notebook, self).update(n=n)
# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
except: # NOQA
# cannot catch KeyboardInterrupt when using manual tqdm
# as the interrupt will most likely happen on another statement
self.disp(bar_style='danger')
raise
# NB: don't `finally: close()`
# since this could be a shared bar which the user will `reset()` | [
266,
274
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def update(self, n=1):
try:
return super(tqdm_notebook, self).update(n=n)
# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt
except: # NOQA
# cannot catch KeyboardInterrupt when using manual tqdm
# as the interrupt will most likely happen on another statement
self.disp(bar_style='danger')
raise
# NB: don't `finally: close()`
# since this could be a shared bar which the user will `reset()` | false | 0 |
790 | tqdm | tqdm.notebook | tqdm_notebook | close | def close(self):
if self.disable:
return
super(tqdm_notebook, self).close()
# Try to detect if there was an error or KeyboardInterrupt
# in manual mode: if n < total, things probably got wrong
if self.total and self.n < self.total:
self.disp(bar_style='danger', check_delay=False)
else:
if self.leave:
self.disp(bar_style='success', check_delay=False)
else:
self.disp(close=True, check_delay=False) | [
278,
290
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def close(self):
if self.disable:
return
super(tqdm_notebook, self).close()
# Try to detect if there was an error or KeyboardInterrupt
# in manual mode: if n < total, things probably got wrong
if self.total and self.n < self.total:
self.disp(bar_style='danger', check_delay=False)
else:
if self.leave:
self.disp(bar_style='success', check_delay=False)
else:
self.disp(close=True, check_delay=False) | true | 2 |
791 | tqdm | tqdm.notebook | tqdm_notebook | clear | def clear(self, *_, **__):
pass | [
292,
293
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def clear(self, *_, **__):
pass | false | 0 |
792 | tqdm | tqdm.notebook | tqdm_notebook | reset | def reset(self, total=None):
"""
Resets to 0 iterations for repeated use.
Consider combining with `leave=True`.
Parameters
----------
total : int or float, optional. Total to use for the new bar.
"""
if self.disable:
return super(tqdm_notebook, self).reset(total=total)
_, pbar, _ = self.container.children
pbar.bar_style = ''
if total is not None:
pbar.max = total
if not self.total and self.ncols is None: # no longer unknown total
pbar.layout.width = None # reset width
return super(tqdm_notebook, self).reset(total=total) | [
295,
313
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | import re
import sys
from weakref import proxy
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']
tqdm = tqdm_notebook
trange = tnrange
class tqdm_notebook(std_tqdm):
def __init__(self, *args, **kwargs):
"""
Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters
----------
display : Whether to call `display(self.container)` immediately
[default: True].
"""
kwargs = kwargs.copy()
# Setup default output
file_kwarg = kwargs.get('file', sys.stderr)
if file_kwarg is sys.stderr or file_kwarg is None:
kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
colour = kwargs.pop('colour', None)
display_here = kwargs.pop('display', True)
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
self.disp = lambda *_, **__: None
return
# Get bar width
self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total)
unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1
total = self.total * unit_scale if self.total else self.total
self.container = self.status_printer(self.fp, total, self.desc, self.ncols)
self.container.pbar = proxy(self)
self.displayed = False
if display_here and self.delay <= 0:
display(self.container)
self.displayed = True
self.disp = self.display
self.colour = colour
# Print initial bar state
if not self.disable:
self.display(check_delay=False)
def reset(self, total=None):
"""
Resets to 0 iterations for repeated use.
Consider combining with `leave=True`.
Parameters
----------
total : int or float, optional. Total to use for the new bar.
"""
if self.disable:
return super(tqdm_notebook, self).reset(total=total)
_, pbar, _ = self.container.children
pbar.bar_style = ''
if total is not None:
pbar.max = total
if not self.total and self.ncols is None: # no longer unknown total
pbar.layout.width = None # reset width
return super(tqdm_notebook, self).reset(total=total) | true | 2 |
793 | tqdm | tqdm.rich | FractionColumn | render | def render(self, task):
"""Calculate common unit for completed and total."""
completed = int(task.completed)
total = int(task.total)
if self.unit_scale:
unit, suffix = filesize.pick_unit_and_suffix(
total,
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
self.unit_divisor,
)
else:
unit, suffix = filesize.pick_unit_and_suffix(total, [""], 1)
precision = 0 if unit == 1 else 1
return Text(
f"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}",
style="progress.download") | [
30,
43
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class FractionColumn(ProgressColumn):
def __init__(self, unit_scale=False, unit_divisor=1000):
self.unit_scale = unit_scale
self.unit_divisor = unit_divisor
super().__init__()
def render(self, task):
"""Calculate common unit for completed and total."""
completed = int(task.completed)
total = int(task.total)
if self.unit_scale:
unit, suffix = filesize.pick_unit_and_suffix(
total,
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
self.unit_divisor,
)
else:
unit, suffix = filesize.pick_unit_and_suffix(total, [""], 1)
precision = 0 if unit == 1 else 1
return Text(
f"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}",
style="progress.download") | true | 2 |
794 | tqdm | tqdm.rich | RateColumn | render | def render(self, task):
"""Show data transfer speed."""
speed = task.speed
if speed is None:
return Text(f"? {self.unit}/s", style="progress.data.speed")
if self.unit_scale:
unit, suffix = filesize.pick_unit_and_suffix(
speed,
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
self.unit_divisor,
)
else:
unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1)
precision = 0 if unit == 1 else 1
return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s",
style="progress.data.speed") | [
56,
70
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class RateColumn(ProgressColumn):
def __init__(self, unit="", unit_scale=False, unit_divisor=1000):
self.unit = unit
self.unit_scale = unit_scale
self.unit_divisor = unit_divisor
super().__init__()
def render(self, task):
"""Show data transfer speed."""
speed = task.speed
if speed is None:
return Text(f"? {self.unit}/s", style="progress.data.speed")
if self.unit_scale:
unit, suffix = filesize.pick_unit_and_suffix(
speed,
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
self.unit_divisor,
)
else:
unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1)
precision = 0 if unit == 1 else 1
return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s",
style="progress.data.speed") | true | 2 |
795 | tqdm | tqdm.rich | tqdm_rich | __init__ | def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d) | [
77,
112
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class FractionColumn(ProgressColumn):
def __init__(self, unit_scale=False, unit_divisor=1000):
self.unit_scale = unit_scale
self.unit_divisor = unit_divisor
super().__init__()
class RateColumn(ProgressColumn):
def __init__(self, unit="", unit_scale=False, unit_divisor=1000):
self.unit = unit
self.unit_scale = unit_scale
self.unit_divisor = unit_divisor
super().__init__()
class tqdm_rich(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d) | false | 0 |
796 | tqdm | tqdm.rich | tqdm_rich | close | def close(self):
if self.disable:
return
super(tqdm_rich, self).close()
self._prog.__exit__(None, None, None) | [
114,
118
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class tqdm_rich(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d)
def close(self):
if self.disable:
return
super(tqdm_rich, self).close()
self._prog.__exit__(None, None, None) | false | 0 |
797 | tqdm | tqdm.rich | tqdm_rich | clear | def clear(self, *_, **__):
pass | [
120,
121
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class tqdm_rich(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d)
def clear(self, *_, **__):
pass | false | 0 |
798 | tqdm | tqdm.rich | tqdm_rich | display | def display(self, *_, **__):
if not hasattr(self, '_prog'):
return
self._prog.update(self._task_id, completed=self.n, description=self.desc) | [
123,
126
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class tqdm_rich(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d)
def display(self, *_, **__):
if not hasattr(self, '_prog'):
return
self._prog.update(self._task_id, completed=self.n, description=self.desc) | false | 0 |
799 | tqdm | tqdm.rich | tqdm_rich | reset | def reset(self, total=None):
"""
Resets to 0 iterations for repeated use.
Parameters
----------
total : int or float, optional. Total to use for the new bar.
"""
if hasattr(self, '_prog'):
self._prog.reset(total=total)
super(tqdm_rich, self).reset(total=total) | [
128,
138
] | false | [
"__author__",
"__all__",
"tqdm",
"trange"
] | from warnings import warn
from rich.progress import (
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarning
from .std import tqdm as std_tqdm
from .utils import _range
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
tqdm = tqdm_rich
trange = trrange
class tqdm_rich(std_tqdm): # pragma: no cover
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
----------
progress : tuple, optional
arguments for `rich.progress.Progress()`.
"""
kwargs = kwargs.copy()
kwargs['gui'] = True
# convert disable = None to False
kwargs['disable'] = bool(kwargs.get('disable', False))
progress = kwargs.pop('progress', None)
super(tqdm_rich, self).__init__(*args, **kwargs)
if self.disable:
return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
d = self.format_dict
if progress is None:
progress = (
"[progress.description]{task.description}"
"[progress.percentage]{task.percentage:>4.0f}%",
BarColumn(bar_width=None),
FractionColumn(
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
unit_divisor=d['unit_divisor']), "]"
)
self._prog = Progress(*progress, transient=not self.leave)
self._prog.__enter__()
self._task_id = self._prog.add_task(self.desc or "", **d)
def reset(self, total=None):
"""
Resets to 0 iterations for repeated use.
Parameters
----------
total : int or float, optional. Total to use for the new bar.
"""
if hasattr(self, '_prog'):
self._prog.reset(total=total)
super(tqdm_rich, self).reset(total=total) | false | 0 |
800 | typesystem | typesystem.base | Position | __eq__ | def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Position)
and self.line_no == other.line_no
and self.column_no == other.column_no
and self.char_index == other.char_index
) | [
10,
11
] | false | [] | import typing
from collections.abc import Mapping
class Position:
def __init__(self, line_no: int, column_no: int, char_index: int):
self.line_no = line_no
self.column_no = column_no
self.char_index = char_index
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, Position)
and self.line_no == other.line_no
and self.column_no == other.column_no
and self.char_index == other.char_index
) | false | 0 |
801 | typesystem | typesystem.base | Message | __eq__ | def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, Message) and (
self.text == other.text
and self.code == other.code
and self.index == other.index
and self.start_position == other.start_position
and self.end_position == other.end_position
) | [
71,
72
] | false | [] | import typing
from collections.abc import Mapping
class Message:
def __init__(
self,
*,
text: str,
code: str = None,
key: typing.Union[int, str] = None,
index: typing.List[typing.Union[int, str]] = None,
position: Position = None,
start_position: Position = None,
end_position: Position = None,
):
"""
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
index - The index of the message within a nested object. eg. ['users', 3, 'username']
Optionally either:
position - The start and end position of the error message within the raw content.
Or:
start_position - The start position of the error message within the raw content.
end_position - The end position of the error message within the raw content.
"""
self.text = text
self.code = "custom" if code is None else code
if key is not None:
assert index is None
self.index = [key]
else:
self.index = [] if index is None else index
if position is None:
self.start_position = start_position
self.end_position = end_position
else:
assert start_position is None
assert end_position is None
self.start_position = position
self.end_position = position
def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, Message) and (
self.text == other.text
and self.code == other.code
and self.index == other.index
and self.start_position == other.start_position
and self.end_position == other.end_position
) | false | 0 |
802 | typesystem | typesystem.base | BaseError | __init__ | def __init__(
self,
*,
text: str = None,
code: str = None,
key: typing.Union[int, str] = None,
position: Position = None,
messages: typing.List[Message] = None,
):
"""
Either instantiated with a single message, like so:
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
Or instantiated with a list of error messages:
messages - A list of all the messages in the error.
"""
if messages is None:
# Instantiated as a ValidationError with a single error message.
assert text is not None
messages = [Message(text=text, code=code, key=key, position=position)]
else:
# Instantiated as a ValidationError with multiple error messages.
assert text is None
assert code is None
assert key is None
assert position is None
assert len(messages)
self._messages = messages
self._message_dict: typing.Dict[
typing.Union[int, str], typing.Union[str, dict]
] = {}
# Populate 'self._message_dict'
for message in messages:
insert_into = self._message_dict
for key in message.index[:-1]:
insert_into = insert_into.setdefault(key, {}) # type: ignore
insert_key = message.index[-1] if message.index else ""
insert_into[insert_key] = message.text | [
111,
154
] | false | [] | import typing
from collections.abc import Mapping
class Position:
def __init__(self, line_no: int, column_no: int, char_index: int):
self.line_no = line_no
self.column_no = column_no
self.char_index = char_index
class Message:
def __init__(
self,
*,
text: str,
code: str = None,
key: typing.Union[int, str] = None,
index: typing.List[typing.Union[int, str]] = None,
position: Position = None,
start_position: Position = None,
end_position: Position = None,
):
"""
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
index - The index of the message within a nested object. eg. ['users', 3, 'username']
Optionally either:
position - The start and end position of the error message within the raw content.
Or:
start_position - The start position of the error message within the raw content.
end_position - The end position of the error message within the raw content.
"""
self.text = text
self.code = "custom" if code is None else code
if key is not None:
assert index is None
self.index = [key]
else:
self.index = [] if index is None else index
if position is None:
self.start_position = start_position
self.end_position = end_position
else:
assert start_position is None
assert end_position is None
self.start_position = position
self.end_position = position
class BaseError(Mapping, Exception):
def __init__(
self,
*,
text: str = None,
code: str = None,
key: typing.Union[int, str] = None,
position: Position = None,
messages: typing.List[Message] = None,
):
"""
Either instantiated with a single message, like so:
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
Or instantiated with a list of error messages:
messages - A list of all the messages in the error.
"""
if messages is None:
# Instantiated as a ValidationError with a single error message.
assert text is not None
messages = [Message(text=text, code=code, key=key, position=position)]
else:
# Instantiated as a ValidationError with multiple error messages.
assert text is None
assert code is None
assert key is None
assert position is None
assert len(messages)
self._messages = messages
self._message_dict: typing.Dict[
typing.Union[int, str], typing.Union[str, dict]
] = {}
# Populate 'self._message_dict'
for message in messages:
insert_into = self._message_dict
for key in message.index[:-1]:
insert_into = insert_into.setdefault(key, {}) # type: ignore
insert_key = message.index[-1] if message.index else ""
insert_into[insert_key] = message.text | true | 2 |
803 | typesystem | typesystem.base | BaseError | __eq__ | def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, ValidationError) and self._messages == other._messages | [
186,
187
] | false | [] | import typing
from collections.abc import Mapping
class BaseError(Mapping, Exception):
def __init__(
self,
*,
text: str = None,
code: str = None,
key: typing.Union[int, str] = None,
position: Position = None,
messages: typing.List[Message] = None,
):
"""
Either instantiated with a single message, like so:
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
Or instantiated with a list of error messages:
messages - A list of all the messages in the error.
"""
if messages is None:
# Instantiated as a ValidationError with a single error message.
assert text is not None
messages = [Message(text=text, code=code, key=key, position=position)]
else:
# Instantiated as a ValidationError with multiple error messages.
assert text is None
assert code is None
assert key is None
assert position is None
assert len(messages)
self._messages = messages
self._message_dict: typing.Dict[
typing.Union[int, str], typing.Union[str, dict]
] = {}
# Populate 'self._message_dict'
for message in messages:
insert_into = self._message_dict
for key in message.index[:-1]:
insert_into = insert_into.setdefault(key, {}) # type: ignore
insert_key = message.index[-1] if message.index else ""
insert_into[insert_key] = message.text
def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, ValidationError) and self._messages == other._messages | false | 0 |
804 | typesystem | typesystem.base | BaseError | __repr__ | def __repr__(self) -> str:
class_name = self.__class__.__name__
if len(self._messages) == 1 and not self._messages[0].index:
message = self._messages[0]
return f"{class_name}(text={message.text!r}, code={message.code!r})"
return f"{class_name}({self._messages!r})" | [
193,
198
] | false | [] | import typing
from collections.abc import Mapping
class BaseError(Mapping, Exception):
def __init__(
self,
*,
text: str = None,
code: str = None,
key: typing.Union[int, str] = None,
position: Position = None,
messages: typing.List[Message] = None,
):
"""
Either instantiated with a single message, like so:
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
Or instantiated with a list of error messages:
messages - A list of all the messages in the error.
"""
if messages is None:
# Instantiated as a ValidationError with a single error message.
assert text is not None
messages = [Message(text=text, code=code, key=key, position=position)]
else:
# Instantiated as a ValidationError with multiple error messages.
assert text is None
assert code is None
assert key is None
assert position is None
assert len(messages)
self._messages = messages
self._message_dict: typing.Dict[
typing.Union[int, str], typing.Union[str, dict]
] = {}
# Populate 'self._message_dict'
for message in messages:
insert_into = self._message_dict
for key in message.index[:-1]:
insert_into = insert_into.setdefault(key, {}) # type: ignore
insert_key = message.index[-1] if message.index else ""
insert_into[insert_key] = message.text
def __repr__(self) -> str:
class_name = self.__class__.__name__
if len(self._messages) == 1 and not self._messages[0].index:
message = self._messages[0]
return f"{class_name}(text={message.text!r}, code={message.code!r})"
return f"{class_name}({self._messages!r})" | true | 2 |
805 | typesystem | typesystem.base | BaseError | __str__ | def __str__(self) -> str:
if len(self._messages) == 1 and not self._messages[0].index:
return self._messages[0].text
return str(dict(self)) | [
200,
203
] | false | [] | import typing
from collections.abc import Mapping
class BaseError(Mapping, Exception):
def __init__(
self,
*,
text: str = None,
code: str = None,
key: typing.Union[int, str] = None,
position: Position = None,
messages: typing.List[Message] = None,
):
"""
Either instantiated with a single message, like so:
text - The error message. 'May not have more than 100 characters'
code - An optional error code, eg. 'max_length'
key - An optional key of the message within a single parent. eg. 'username'
Or instantiated with a list of error messages:
messages - A list of all the messages in the error.
"""
if messages is None:
# Instantiated as a ValidationError with a single error message.
assert text is not None
messages = [Message(text=text, code=code, key=key, position=position)]
else:
# Instantiated as a ValidationError with multiple error messages.
assert text is None
assert code is None
assert key is None
assert position is None
assert len(messages)
self._messages = messages
self._message_dict: typing.Dict[
typing.Union[int, str], typing.Union[str, dict]
] = {}
# Populate 'self._message_dict'
for message in messages:
insert_into = self._message_dict
for key in message.index[:-1]:
insert_into = insert_into.setdefault(key, {}) # type: ignore
insert_key = message.index[-1] if message.index else ""
insert_into[insert_key] = message.text
def __str__(self) -> str:
if len(self._messages) == 1 and not self._messages[0].index:
return self._messages[0].text
return str(dict(self)) | true | 2 |
806 | typesystem | typesystem.base | ValidationResult | __iter__ | def __iter__(self) -> typing.Iterator:
yield self.value
yield self.error | [
242,
244
] | false | [] | import typing
from collections.abc import Mapping
class ValidationResult:
def __init__(
self, *, value: typing.Any = None, error: ValidationError = None
) -> None:
"""
Either:
value - The validated data.
Or:
error - The validation error.
"""
assert value is None or error is None
self.value = value
self.error = error
def __iter__(self) -> typing.Iterator:
yield self.value
yield self.error | false | 0 |
807 | typesystem | typesystem.composites | NeverMatch | __init__ | def __init__(self, **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs) | [
14,
16
] | false | [] | import typing
from typesystem.fields import Any, Field
class NeverMatch(Field):
errors = {"never": "This never validates."}
def __init__(self, **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs) | false | 0 |
808 | typesystem | typesystem.composites | OneOf | __init__ | def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.one_of = one_of | [
35,
38
] | false | [] | import typing
from typesystem.fields import Any, Field
class OneOf(Field):
errors = {
"no_match": "Did not match any valid type.",
"multiple_matches": "Matched more than one type.",
}
def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.one_of = one_of | false | 0 |
809 | typesystem | typesystem.composites | OneOf | validate | def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
candidate = None
match_count = 0
for child in self.one_of:
validated, error = child.validate_or_error(value, strict=strict)
if error is None:
match_count += 1
candidate = validated
if match_count == 1:
return candidate
elif match_count > 1:
raise self.validation_error("multiple_matches")
raise self.validation_error("no_match") | [
40,
53
] | false | [] | import typing
from typesystem.fields import Any, Field
class OneOf(Field):
errors = {
"no_match": "Did not match any valid type.",
"multiple_matches": "Matched more than one type.",
}
def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.one_of = one_of
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
candidate = None
match_count = 0
for child in self.one_of:
validated, error = child.validate_or_error(value, strict=strict)
if error is None:
match_count += 1
candidate = validated
if match_count == 1:
return candidate
elif match_count > 1:
raise self.validation_error("multiple_matches")
raise self.validation_error("no_match") | true | 2 |
810 | typesystem | typesystem.composites | AllOf | __init__ | def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.all_of = all_of | [
64,
67
] | false | [] | import typing
from typesystem.fields import Any, Field
class AllOf(Field):
def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.all_of = all_of | false | 0 |
811 | typesystem | typesystem.composites | Not | __init__ | def __init__(self, negated: Field, **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.negated = negated | [
84,
87
] | false | [] | import typing
from typesystem.fields import Any, Field
class Not(Field):
errors = {"negated": "Must not match."}
def __init__(self, negated: Field, **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.negated = negated | false | 0 |
812 | typesystem | typesystem.composites | Not | validate | def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
_, error = self.negated.validate_or_error(value, strict=strict)
if error:
return value
raise self.validation_error("negated") | [
89,
93
] | false | [] | import typing
from typesystem.fields import Any, Field
class Not(Field):
errors = {"negated": "Must not match."}
def __init__(self, negated: Field, **kwargs: typing.Any) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.negated = negated
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
_, error = self.negated.validate_or_error(value, strict=strict)
if error:
return value
raise self.validation_error("negated") | true | 2 |
813 | typesystem | typesystem.composites | IfThenElse | __init__ | def __init__(
self,
if_clause: Field,
then_clause: Field = None,
else_clause: Field = None,
**kwargs: typing.Any
) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.if_clause = if_clause
self.then_clause = Any() if then_clause is None else then_clause
self.else_clause = Any() if else_clause is None else else_clause | [
103,
114
] | false | [] | import typing
from typesystem.fields import Any, Field
class IfThenElse(Field):
def __init__(
self,
if_clause: Field,
then_clause: Field = None,
else_clause: Field = None,
**kwargs: typing.Any
) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.if_clause = if_clause
self.then_clause = Any() if then_clause is None else then_clause
self.else_clause = Any() if else_clause is None else else_clause | false | 0 |
814 | typesystem | typesystem.composites | IfThenElse | validate | def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
_, error = self.if_clause.validate_or_error(value, strict=strict)
if error is None:
return self.then_clause.validate(value, strict=strict)
else:
return self.else_clause.validate(value, strict=strict) | [
116,
121
] | false | [] | import typing
from typesystem.fields import Any, Field
class IfThenElse(Field):
def __init__(
self,
if_clause: Field,
then_clause: Field = None,
else_clause: Field = None,
**kwargs: typing.Any
) -> None:
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.if_clause = if_clause
self.then_clause = Any() if then_clause is None else then_clause
self.else_clause = Any() if else_clause is None else else_clause
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
_, error = self.if_clause.validate_or_error(value, strict=strict)
if error is None:
return self.then_clause.validate(value, strict=strict)
else:
return self.else_clause.validate(value, strict=strict) | true | 2 |
815 | typesystem | typesystem.fields | Field | validate_or_error | def validate_or_error(
self, value: typing.Any, *, strict: bool = False
) -> ValidationResult:
try:
value = self.validate(value, strict=strict)
except ValidationError as error:
return ValidationResult(value=None, error=error)
return ValidationResult(value=value, error=None) | [
52,
59
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
def validate_or_error(
self, value: typing.Any, *, strict: bool = False
) -> ValidationResult:
try:
value = self.validate(value, strict=strict)
except ValidationError as error:
return ValidationResult(value=None, error=error)
return ValidationResult(value=value, error=None) | false | 0 |
816 | typesystem | typesystem.fields | Field | get_default_value | def get_default_value(self) -> typing.Any:
default = getattr(self, "default", None)
if callable(default):
return default()
return default | [
67,
71
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
def get_default_value(self) -> typing.Any:
default = getattr(self, "default", None)
if callable(default):
return default()
return default | true | 2 |
817 | typesystem | typesystem.fields | Field | __or__ | def __or__(self, other: "Field") -> "Union":
if isinstance(self, Union):
any_of = self.any_of
else:
any_of = [self]
if isinstance(other, Union):
any_of += other.any_of
else:
any_of += [other]
return Union(any_of=any_of) | [
80,
91
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Union(Field):
errors = {"null": "May not be null.", "union": "Did not match any valid type."}
def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):
super().__init__(**kwargs)
self.any_of = any_of
if any([child.allow_null for child in any_of]):
self.allow_null = True
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
def __or__(self, other: "Field") -> "Union":
if isinstance(self, Union):
any_of = self.any_of
else:
any_of = [self]
if isinstance(other, Union):
any_of += other.any_of
else:
any_of += [other]
return Union(any_of=any_of) | true | 2 |
818 | typesystem | typesystem.fields | String | __init__ | def __init__(
self,
*,
allow_blank: bool = False,
trim_whitespace: bool = True,
max_length: int = None,
min_length: int = None,
pattern: typing.Union[str, typing.Pattern] = None,
format: str = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
assert max_length is None or isinstance(max_length, int)
assert min_length is None or isinstance(min_length, int)
assert pattern is None or isinstance(pattern, (str, typing.Pattern))
assert format is None or isinstance(format, str)
if allow_blank and not self.has_default():
self.default = ""
self.allow_blank = allow_blank
self.trim_whitespace = trim_whitespace
self.max_length = max_length
self.min_length = min_length
self.format = format
if pattern is None:
self.pattern = None
self.pattern_regex = None
elif isinstance(pattern, str):
self.pattern = pattern
self.pattern_regex = re.compile(pattern)
else:
self.pattern = pattern.pattern
self.pattern_regex = pattern | [
105,
140
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Union(Field):
errors = {"null": "May not be null.", "union": "Did not match any valid type."}
def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):
super().__init__(**kwargs)
self.any_of = any_of
if any([child.allow_null for child in any_of]):
self.allow_null = True
class String(Field):
errors = {
"type": "Must be a string.",
"null": "May not be null.",
"blank": "Must not be blank.",
"max_length": "Must have no more than {max_length} characters.",
"min_length": "Must have at least {min_length} characters.",
"pattern": "Must match the pattern /{pattern}/.",
"format": "Must be a valid {format}.",
}
def __init__(
self,
*,
allow_blank: bool = False,
trim_whitespace: bool = True,
max_length: int = None,
min_length: int = None,
pattern: typing.Union[str, typing.Pattern] = None,
format: str = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
assert max_length is None or isinstance(max_length, int)
assert min_length is None or isinstance(min_length, int)
assert pattern is None or isinstance(pattern, (str, typing.Pattern))
assert format is None or isinstance(format, str)
if allow_blank and not self.has_default():
self.default = ""
self.allow_blank = allow_blank
self.trim_whitespace = trim_whitespace
self.max_length = max_length
self.min_length = min_length
self.format = format
if pattern is None:
self.pattern = None
self.pattern_regex = None
elif isinstance(pattern, str):
self.pattern = pattern
self.pattern_regex = re.compile(pattern)
else:
self.pattern = pattern.pattern
self.pattern_regex = pattern | true | 2 |
819 | typesystem | typesystem.fields | String | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None and self.allow_blank and not strict:
# Leniently cast nulls to empty strings if allow_blank.
return ""
elif value is None:
raise self.validation_error("null")
elif self.format in FORMATS and FORMATS[self.format].is_native_type(value):
return value
elif not isinstance(value, str):
raise self.validation_error("type")
# The null character is always invalid.
value = value.replace("\0", "")
# Strip leading/trailing whitespace by default.
if self.trim_whitespace:
value = value.strip()
if not self.allow_blank and not value:
if self.allow_null and not strict:
# Leniently cast empty strings (after trimming) to null if allow_null.
return None
raise self.validation_error("blank")
if self.min_length is not None:
if len(value) < self.min_length:
raise self.validation_error("min_length")
if self.max_length is not None:
if len(value) > self.max_length:
raise self.validation_error("max_length")
if self.pattern_regex is not None:
if not self.pattern_regex.search(value):
raise self.validation_error("pattern")
if self.format in FORMATS:
return FORMATS[self.format].validate(value)
return value | [
142,
183
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class String(Field):
errors = {
"type": "Must be a string.",
"null": "May not be null.",
"blank": "Must not be blank.",
"max_length": "Must have no more than {max_length} characters.",
"min_length": "Must have at least {min_length} characters.",
"pattern": "Must match the pattern /{pattern}/.",
"format": "Must be a valid {format}.",
}
def __init__(
self,
*,
allow_blank: bool = False,
trim_whitespace: bool = True,
max_length: int = None,
min_length: int = None,
pattern: typing.Union[str, typing.Pattern] = None,
format: str = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
assert max_length is None or isinstance(max_length, int)
assert min_length is None or isinstance(min_length, int)
assert pattern is None or isinstance(pattern, (str, typing.Pattern))
assert format is None or isinstance(format, str)
if allow_blank and not self.has_default():
self.default = ""
self.allow_blank = allow_blank
self.trim_whitespace = trim_whitespace
self.max_length = max_length
self.min_length = min_length
self.format = format
if pattern is None:
self.pattern = None
self.pattern_regex = None
elif isinstance(pattern, str):
self.pattern = pattern
self.pattern_regex = re.compile(pattern)
else:
self.pattern = pattern.pattern
self.pattern_regex = pattern
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None and self.allow_blank and not strict:
# Leniently cast nulls to empty strings if allow_blank.
return ""
elif value is None:
raise self.validation_error("null")
elif self.format in FORMATS and FORMATS[self.format].is_native_type(value):
return value
elif not isinstance(value, str):
raise self.validation_error("type")
# The null character is always invalid.
value = value.replace("\0", "")
# Strip leading/trailing whitespace by default.
if self.trim_whitespace:
value = value.strip()
if not self.allow_blank and not value:
if self.allow_null and not strict:
# Leniently cast empty strings (after trimming) to null if allow_null.
return None
raise self.validation_error("blank")
if self.min_length is not None:
if len(value) < self.min_length:
raise self.validation_error("min_length")
if self.max_length is not None:
if len(value) > self.max_length:
raise self.validation_error("max_length")
if self.pattern_regex is not None:
if not self.pattern_regex.search(value):
raise self.validation_error("pattern")
if self.format in FORMATS:
return FORMATS[self.format].validate(value)
return value | true | 2 |
820 | typesystem | typesystem.fields | String | serialize | def serialize(self, obj: typing.Any) -> typing.Any:
if self.format in FORMATS:
return FORMATS[self.format].serialize(obj)
return obj | [
185,
188
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class String(Field):
errors = {
"type": "Must be a string.",
"null": "May not be null.",
"blank": "Must not be blank.",
"max_length": "Must have no more than {max_length} characters.",
"min_length": "Must have at least {min_length} characters.",
"pattern": "Must match the pattern /{pattern}/.",
"format": "Must be a valid {format}.",
}
def __init__(
self,
*,
allow_blank: bool = False,
trim_whitespace: bool = True,
max_length: int = None,
min_length: int = None,
pattern: typing.Union[str, typing.Pattern] = None,
format: str = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
assert max_length is None or isinstance(max_length, int)
assert min_length is None or isinstance(min_length, int)
assert pattern is None or isinstance(pattern, (str, typing.Pattern))
assert format is None or isinstance(format, str)
if allow_blank and not self.has_default():
self.default = ""
self.allow_blank = allow_blank
self.trim_whitespace = trim_whitespace
self.max_length = max_length
self.min_length = min_length
self.format = format
if pattern is None:
self.pattern = None
self.pattern_regex = None
elif isinstance(pattern, str):
self.pattern = pattern
self.pattern_regex = re.compile(pattern)
else:
self.pattern = pattern.pattern
self.pattern_regex = pattern
def serialize(self, obj: typing.Any) -> typing.Any:
if self.format in FORMATS:
return FORMATS[self.format].serialize(obj)
return obj | true | 2 |
821 | typesystem | typesystem.fields | Number | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value == "" and self.allow_null and not strict:
return None
elif value is None:
raise self.validation_error("null")
elif isinstance(value, bool):
raise self.validation_error("type")
elif (
self.numeric_type is int
and isinstance(value, float)
and not value.is_integer()
):
raise self.validation_error("integer")
elif not isinstance(value, (int, float)) and strict:
raise self.validation_error("type")
try:
if isinstance(value, str):
# Casting to a decimal first gives more lenient parsing.
value = decimal.Decimal(value)
if self.numeric_type is not None:
value = self.numeric_type(value)
except (TypeError, ValueError, decimal.InvalidOperation):
raise self.validation_error("type")
if not isfinite(value):
# inf, -inf, nan, are all invalid.
raise self.validation_error("finite")
if self.precision is not None:
numeric_type = self.numeric_type or type(value)
quantize_val = decimal.Decimal(self.precision)
decimal_val = decimal.Decimal(value)
decimal_val = decimal_val.quantize(
quantize_val, rounding=decimal.ROUND_HALF_UP
)
value = numeric_type(decimal_val)
if self.minimum is not None and value < self.minimum:
raise self.validation_error("minimum")
if self.exclusive_minimum is not None and value <= self.exclusive_minimum:
raise self.validation_error("exclusive_minimum")
if self.maximum is not None and value > self.maximum:
raise self.validation_error("maximum")
if self.exclusive_maximum is not None and value >= self.exclusive_maximum:
raise self.validation_error("exclusive_maximum")
if self.multiple_of is not None:
if isinstance(self.multiple_of, int):
if value % self.multiple_of:
raise self.validation_error("multiple_of")
else:
if not (value * (1 / self.multiple_of)).is_integer():
raise self.validation_error("multiple_of")
return value | [
237,
297
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Number(Field):
numeric_type: typing.Optional[type] = None
errors = {
"type": "Must be a number.",
"null": "May not be null.",
"integer": "Must be an integer.",
"finite": "Must be finite.",
"minimum": "Must be greater than or equal to {minimum}.",
"exclusive_minimum": "Must be greater than {exclusive_minimum}.",
"maximum": "Must be less than or equal to {maximum}.",
"exclusive_maximum": "Must be less than {exclusive_maximum}.",
"multiple_of": "Must be a multiple of {multiple_of}.",
}
def __init__(
self,
*,
minimum: typing.Union[int, float, decimal.Decimal] = None,
maximum: typing.Union[int, float, decimal.Decimal] = None,
exclusive_minimum: typing.Union[int, float, decimal.Decimal] = None,
exclusive_maximum: typing.Union[int, float, decimal.Decimal] = None,
precision: str = None,
multiple_of: typing.Union[int, float, decimal.Decimal] = None,
**kwargs: typing.Any,
):
super().__init__(**kwargs)
assert minimum is None or isinstance(minimum, (int, float, decimal.Decimal))
assert maximum is None or isinstance(maximum, (int, float, decimal.Decimal))
assert exclusive_minimum is None or isinstance(
exclusive_minimum, (int, float, decimal.Decimal)
)
assert exclusive_maximum is None or isinstance(
exclusive_maximum, (int, float, decimal.Decimal)
)
assert multiple_of is None or isinstance(
multiple_of, (int, float, decimal.Decimal)
)
self.minimum = minimum
self.maximum = maximum
self.exclusive_minimum = exclusive_minimum
self.exclusive_maximum = exclusive_maximum
self.multiple_of = multiple_of
self.precision = precision
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value == "" and self.allow_null and not strict:
return None
elif value is None:
raise self.validation_error("null")
elif isinstance(value, bool):
raise self.validation_error("type")
elif (
self.numeric_type is int
and isinstance(value, float)
and not value.is_integer()
):
raise self.validation_error("integer")
elif not isinstance(value, (int, float)) and strict:
raise self.validation_error("type")
try:
if isinstance(value, str):
# Casting to a decimal first gives more lenient parsing.
value = decimal.Decimal(value)
if self.numeric_type is not None:
value = self.numeric_type(value)
except (TypeError, ValueError, decimal.InvalidOperation):
raise self.validation_error("type")
if not isfinite(value):
# inf, -inf, nan, are all invalid.
raise self.validation_error("finite")
if self.precision is not None:
numeric_type = self.numeric_type or type(value)
quantize_val = decimal.Decimal(self.precision)
decimal_val = decimal.Decimal(value)
decimal_val = decimal_val.quantize(
quantize_val, rounding=decimal.ROUND_HALF_UP
)
value = numeric_type(decimal_val)
if self.minimum is not None and value < self.minimum:
raise self.validation_error("minimum")
if self.exclusive_minimum is not None and value <= self.exclusive_minimum:
raise self.validation_error("exclusive_minimum")
if self.maximum is not None and value > self.maximum:
raise self.validation_error("maximum")
if self.exclusive_maximum is not None and value >= self.exclusive_maximum:
raise self.validation_error("exclusive_maximum")
if self.multiple_of is not None:
if isinstance(self.multiple_of, int):
if value % self.multiple_of:
raise self.validation_error("multiple_of")
else:
if not (value * (1 / self.multiple_of)).is_integer():
raise self.validation_error("multiple_of")
return value | true | 2 |
822 | typesystem | typesystem.fields | Boolean | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, bool):
if strict:
raise self.validation_error("type")
if isinstance(value, str):
value = value.lower()
if self.allow_null and value in self.coerce_null_values:
return None
try:
value = self.coerce_values[value]
except (KeyError, TypeError):
raise self.validation_error("type")
return value | [
330,
352
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Boolean(Field):
errors = {"type": "Must be a boolean.", "null": "May not be null."}
coerce_values = {
"true": True,
"false": False,
"on": True,
"off": False,
"1": True,
"0": False,
"": False,
1: True,
0: False,
}
coerce_null_values = {"", "null", "none"}
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, bool):
if strict:
raise self.validation_error("type")
if isinstance(value, str):
value = value.lower()
if self.allow_null and value in self.coerce_null_values:
return None
try:
value = self.coerce_values[value]
except (KeyError, TypeError):
raise self.validation_error("type")
return value | true | 2 |
823 | typesystem | typesystem.fields | Choice | __init__ | def __init__(
self,
*,
choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
self.choices = [
(choice if isinstance(choice, (tuple, list)) else (choice, choice))
for choice in choices or []
]
assert all(len(choice) == 2 for choice in self.choices) | [
362,
373
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Union(Field):
errors = {"null": "May not be null.", "union": "Did not match any valid type."}
def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):
super().__init__(**kwargs)
self.any_of = any_of
if any([child.allow_null for child in any_of]):
self.allow_null = True
class Choice(Field):
errors = {
"null": "May not be null.",
"required": "This field is required.",
"choice": "Not a valid choice.",
}
def __init__(
self,
*,
choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
self.choices = [
(choice if isinstance(choice, (tuple, list)) else (choice, choice))
for choice in choices or []
]
assert all(len(choice) == 2 for choice in self.choices) | false | 0 |
824 | typesystem | typesystem.fields | Choice | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif value not in Uniqueness([key for key, value in self.choices]):
if value == "":
if self.allow_null and not strict:
return None
raise self.validation_error("required")
raise self.validation_error("choice")
return value | [
375,
386
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Choice(Field):
errors = {
"null": "May not be null.",
"required": "This field is required.",
"choice": "Not a valid choice.",
}
def __init__(
self,
*,
choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
self.choices = [
(choice if isinstance(choice, (tuple, list)) else (choice, choice))
for choice in choices or []
]
assert all(len(choice) == 2 for choice in self.choices)
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif value not in Uniqueness([key for key, value in self.choices]):
if value == "":
if self.allow_null and not strict:
return None
raise self.validation_error("required")
raise self.validation_error("choice")
return value | true | 2 |
825 | typesystem | typesystem.fields | Object | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, (dict, typing.Mapping)):
raise self.validation_error("type")
validated = {}
error_messages = []
# Ensure all property keys are strings.
for key in value.keys():
if not isinstance(key, str):
text = self.get_error_text("invalid_key")
message = Message(text=text, code="invalid_key", index=[key])
error_messages.append(message)
elif self.property_names is not None:
_, error = self.property_names.validate_or_error(key)
if error is not None:
text = self.get_error_text("invalid_property")
message = Message(text=text, code="invalid_property", index=[key])
error_messages.append(message)
# Min/Max properties
if self.min_properties is not None:
if len(value) < self.min_properties:
if self.min_properties == 1:
raise self.validation_error("empty")
else:
raise self.validation_error("min_properties")
if self.max_properties is not None:
if len(value) > self.max_properties:
raise self.validation_error("max_properties")
# Required properties
for key in self.required:
if key not in value:
text = self.get_error_text("required")
message = Message(text=text, code="required", index=[key])
error_messages.append(message)
# Properties
for key, child_schema in self.properties.items():
if key not in value:
if child_schema.has_default():
validated[key] = child_schema.get_default_value()
continue
item = value[key]
child_value, error = child_schema.validate_or_error(item, strict=strict)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
# Pattern properties
if self.pattern_properties:
for key in list(value.keys()):
for pattern, child_schema in self.pattern_properties.items():
if isinstance(key, str) and re.search(pattern, key):
item = value[key]
child_value, error = child_schema.validate_or_error(
item, strict=strict
)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
# Additional properties
validated_keys = set(validated.keys())
error_keys = set(
[message.index[0] for message in error_messages if message.index]
)
remaining = [
key for key in value.keys() if key not in validated_keys | error_keys
]
if self.additional_properties is True:
for key in remaining:
validated[key] = value[key]
elif self.additional_properties is False:
for key in remaining:
text = self.get_error_text("invalid_property")
message = Message(text=text, code="invalid_property", key=key)
error_messages.append(message)
elif self.additional_properties is not None:
assert isinstance(self.additional_properties, Field)
child_schema = self.additional_properties
for key in remaining:
item = value[key]
child_value, error = child_schema.validate_or_error(item, strict=strict)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
if error_messages:
raise ValidationError(messages=error_messages)
return validated | [
445,
546
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
class Object(Field):
errors = {
"type": "Must be an object.",
"null": "May not be null.",
"invalid_key": "All object keys must be strings.",
"required": "This field is required.",
"invalid_property": "Invalid property name.",
"empty": "Must not be empty.",
"max_properties": "Must have no more than {max_properties} properties.",
"min_properties": "Must have at least {min_properties} properties.",
}
def __init__(
self,
*,
properties: typing.Dict[str, Field] = None,
pattern_properties: typing.Dict[str, Field] = None,
additional_properties: typing.Union[bool, None, Field] = True,
property_names: Field = None,
min_properties: int = None,
max_properties: int = None,
required: typing.Sequence[str] = None,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
if isinstance(properties, Field):
additional_properties = properties
properties = None
properties = {} if (properties is None) else dict(properties)
pattern_properties = (
{} if (pattern_properties is None) else dict(pattern_properties)
)
required = list(required) if isinstance(required, (list, tuple)) else required
required = [] if (required is None) else required
assert all(isinstance(k, str) for k in properties.keys())
assert all(isinstance(v, Field) for v in properties.values())
assert all(isinstance(k, str) for k in pattern_properties.keys())
assert all(isinstance(v, Field) for v in pattern_properties.values())
assert additional_properties in (None, True, False) or isinstance(
additional_properties, Field
)
assert min_properties is None or isinstance(min_properties, int)
assert max_properties is None or isinstance(max_properties, int)
assert all(isinstance(i, str) for i in required)
self.properties = properties
self.pattern_properties = pattern_properties
self.additional_properties = additional_properties
self.property_names = property_names
self.min_properties = min_properties
self.max_properties = max_properties
self.required = required
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, (dict, typing.Mapping)):
raise self.validation_error("type")
validated = {}
error_messages = []
# Ensure all property keys are strings.
for key in value.keys():
if not isinstance(key, str):
text = self.get_error_text("invalid_key")
message = Message(text=text, code="invalid_key", index=[key])
error_messages.append(message)
elif self.property_names is not None:
_, error = self.property_names.validate_or_error(key)
if error is not None:
text = self.get_error_text("invalid_property")
message = Message(text=text, code="invalid_property", index=[key])
error_messages.append(message)
# Min/Max properties
if self.min_properties is not None:
if len(value) < self.min_properties:
if self.min_properties == 1:
raise self.validation_error("empty")
else:
raise self.validation_error("min_properties")
if self.max_properties is not None:
if len(value) > self.max_properties:
raise self.validation_error("max_properties")
# Required properties
for key in self.required:
if key not in value:
text = self.get_error_text("required")
message = Message(text=text, code="required", index=[key])
error_messages.append(message)
# Properties
for key, child_schema in self.properties.items():
if key not in value:
if child_schema.has_default():
validated[key] = child_schema.get_default_value()
continue
item = value[key]
child_value, error = child_schema.validate_or_error(item, strict=strict)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
# Pattern properties
if self.pattern_properties:
for key in list(value.keys()):
for pattern, child_schema in self.pattern_properties.items():
if isinstance(key, str) and re.search(pattern, key):
item = value[key]
child_value, error = child_schema.validate_or_error(
item, strict=strict
)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
# Additional properties
validated_keys = set(validated.keys())
error_keys = set(
[message.index[0] for message in error_messages if message.index]
)
remaining = [
key for key in value.keys() if key not in validated_keys | error_keys
]
if self.additional_properties is True:
for key in remaining:
validated[key] = value[key]
elif self.additional_properties is False:
for key in remaining:
text = self.get_error_text("invalid_property")
message = Message(text=text, code="invalid_property", key=key)
error_messages.append(message)
elif self.additional_properties is not None:
assert isinstance(self.additional_properties, Field)
child_schema = self.additional_properties
for key in remaining:
item = value[key]
child_value, error = child_schema.validate_or_error(item, strict=strict)
if not error:
validated[key] = child_value
else:
error_messages += error.messages(add_prefix=key)
if error_messages:
raise ValidationError(messages=error_messages)
return validated | true | 2 |
826 | typesystem | typesystem.fields | Array | __init__ | def __init__(
self,
items: typing.Union[Field, typing.Sequence[Field]] = None,
additional_items: typing.Union[Field, bool] = False,
min_items: int = None,
max_items: int = None,
exact_items: int = None,
unique_items: bool = False,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
items = list(items) if isinstance(items, (list, tuple)) else items
assert (
items is None
or isinstance(items, Field)
or (isinstance(items, list) and all(isinstance(i, Field) for i in items))
)
assert isinstance(additional_items, bool) or isinstance(additional_items, Field)
assert min_items is None or isinstance(min_items, int)
assert max_items is None or isinstance(max_items, int)
assert isinstance(unique_items, bool)
if isinstance(items, list):
if min_items is None:
min_items = len(items)
if max_items is None and (additional_items is False):
max_items = len(items)
if exact_items is not None:
min_items = exact_items
max_items = exact_items
self.items = items
self.additional_items = additional_items
self.min_items = min_items
self.max_items = max_items
self.unique_items = unique_items | [
561,
599
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
class Union(Field):
errors = {"null": "May not be null.", "union": "Did not match any valid type."}
def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):
super().__init__(**kwargs)
self.any_of = any_of
if any([child.allow_null for child in any_of]):
self.allow_null = True
class Array(Field):
errors = {
"type": "Must be an array.",
"null": "May not be null.",
"empty": "Must not be empty.",
"exact_items": "Must have {min_items} items.",
"min_items": "Must have at least {min_items} items.",
"max_items": "Must have no more than {max_items} items.",
"additional_items": "May not contain additional items.",
"unique_items": "Items must be unique.",
}
def __init__(
self,
items: typing.Union[Field, typing.Sequence[Field]] = None,
additional_items: typing.Union[Field, bool] = False,
min_items: int = None,
max_items: int = None,
exact_items: int = None,
unique_items: bool = False,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
items = list(items) if isinstance(items, (list, tuple)) else items
assert (
items is None
or isinstance(items, Field)
or (isinstance(items, list) and all(isinstance(i, Field) for i in items))
)
assert isinstance(additional_items, bool) or isinstance(additional_items, Field)
assert min_items is None or isinstance(min_items, int)
assert max_items is None or isinstance(max_items, int)
assert isinstance(unique_items, bool)
if isinstance(items, list):
if min_items is None:
min_items = len(items)
if max_items is None and (additional_items is False):
max_items = len(items)
if exact_items is not None:
min_items = exact_items
max_items = exact_items
self.items = items
self.additional_items = additional_items
self.min_items = min_items
self.max_items = max_items
self.unique_items = unique_items | true | 2 |
827 | typesystem | typesystem.fields | Array | validate | def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, list):
raise self.validation_error("type")
if (
self.min_items is not None
and self.min_items == self.max_items
and len(value) != self.min_items
):
raise self.validation_error("exact_items")
if self.min_items is not None and len(value) < self.min_items:
if self.min_items == 1:
raise self.validation_error("empty")
raise self.validation_error("min_items")
elif self.max_items is not None and len(value) > self.max_items:
raise self.validation_error("max_items")
# Ensure all items are of the right type.
validated = []
error_messages: typing.List[Message] = []
if self.unique_items:
seen_items = Uniqueness()
for pos, item in enumerate(value):
validator = None
if isinstance(self.items, list):
if pos < len(self.items):
validator = self.items[pos]
elif isinstance(self.additional_items, Field):
validator = self.additional_items
elif self.items is not None:
validator = self.items
if validator is None:
validated.append(item)
else:
item, error = validator.validate_or_error(item, strict=strict)
if error:
error_messages += error.messages(add_prefix=pos)
else:
validated.append(item)
if self.unique_items:
if item in seen_items:
text = self.get_error_text("unique_items")
message = Message(text=text, code="unique_items", key=pos)
error_messages.append(message)
else:
seen_items.add(item)
if error_messages:
raise ValidationError(messages=error_messages)
return validated | [
601,
658
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Field:
errors: typing.Dict[str, str] = {}
_creation_counter = 0
def __init__(
self,
*,
title: str = "",
description: str = "",
default: typing.Any = NO_DEFAULT,
allow_null: bool = False,
):
assert isinstance(title, str)
assert isinstance(description, str)
if allow_null and default is NO_DEFAULT:
default = None
if default is not NO_DEFAULT:
self.default = default
self.title = title
self.description = description
self.allow_null = allow_null
# We need this global counter to determine what order fields have
# been declared in when used with `Schema`.
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
class Array(Field):
errors = {
"type": "Must be an array.",
"null": "May not be null.",
"empty": "Must not be empty.",
"exact_items": "Must have {min_items} items.",
"min_items": "Must have at least {min_items} items.",
"max_items": "Must have no more than {max_items} items.",
"additional_items": "May not contain additional items.",
"unique_items": "Items must be unique.",
}
def __init__(
self,
items: typing.Union[Field, typing.Sequence[Field]] = None,
additional_items: typing.Union[Field, bool] = False,
min_items: int = None,
max_items: int = None,
exact_items: int = None,
unique_items: bool = False,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
items = list(items) if isinstance(items, (list, tuple)) else items
assert (
items is None
or isinstance(items, Field)
or (isinstance(items, list) and all(isinstance(i, Field) for i in items))
)
assert isinstance(additional_items, bool) or isinstance(additional_items, Field)
assert min_items is None or isinstance(min_items, int)
assert max_items is None or isinstance(max_items, int)
assert isinstance(unique_items, bool)
if isinstance(items, list):
if min_items is None:
min_items = len(items)
if max_items is None and (additional_items is False):
max_items = len(items)
if exact_items is not None:
min_items = exact_items
max_items = exact_items
self.items = items
self.additional_items = additional_items
self.min_items = min_items
self.max_items = max_items
self.unique_items = unique_items
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
elif not isinstance(value, list):
raise self.validation_error("type")
if (
self.min_items is not None
and self.min_items == self.max_items
and len(value) != self.min_items
):
raise self.validation_error("exact_items")
if self.min_items is not None and len(value) < self.min_items:
if self.min_items == 1:
raise self.validation_error("empty")
raise self.validation_error("min_items")
elif self.max_items is not None and len(value) > self.max_items:
raise self.validation_error("max_items")
# Ensure all items are of the right type.
validated = []
error_messages: typing.List[Message] = []
if self.unique_items:
seen_items = Uniqueness()
for pos, item in enumerate(value):
validator = None
if isinstance(self.items, list):
if pos < len(self.items):
validator = self.items[pos]
elif isinstance(self.additional_items, Field):
validator = self.additional_items
elif self.items is not None:
validator = self.items
if validator is None:
validated.append(item)
else:
item, error = validator.validate_or_error(item, strict=strict)
if error:
error_messages += error.messages(add_prefix=pos)
else:
validated.append(item)
if self.unique_items:
if item in seen_items:
text = self.get_error_text("unique_items")
message = Message(text=text, code="unique_items", key=pos)
error_messages.append(message)
else:
seen_items.add(item)
if error_messages:
raise ValidationError(messages=error_messages)
return validated | true | 2 |
828 | typesystem | typesystem.fields | Array | serialize | def serialize(self, obj: typing.Any) -> typing.Any:
if obj is None:
return None
if isinstance(self.items, list):
return [
serializer.serialize(value)
for serializer, value in zip(self.items, obj)
]
if self.items is None:
return obj
return [self.items.serialize(value) for value in obj] | [
660,
673
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Array(Field):
errors = {
"type": "Must be an array.",
"null": "May not be null.",
"empty": "Must not be empty.",
"exact_items": "Must have {min_items} items.",
"min_items": "Must have at least {min_items} items.",
"max_items": "Must have no more than {max_items} items.",
"additional_items": "May not contain additional items.",
"unique_items": "Items must be unique.",
}
def __init__(
self,
items: typing.Union[Field, typing.Sequence[Field]] = None,
additional_items: typing.Union[Field, bool] = False,
min_items: int = None,
max_items: int = None,
exact_items: int = None,
unique_items: bool = False,
**kwargs: typing.Any,
) -> None:
super().__init__(**kwargs)
items = list(items) if isinstance(items, (list, tuple)) else items
assert (
items is None
or isinstance(items, Field)
or (isinstance(items, list) and all(isinstance(i, Field) for i in items))
)
assert isinstance(additional_items, bool) or isinstance(additional_items, Field)
assert min_items is None or isinstance(min_items, int)
assert max_items is None or isinstance(max_items, int)
assert isinstance(unique_items, bool)
if isinstance(items, list):
if min_items is None:
min_items = len(items)
if max_items is None and (additional_items is False):
max_items = len(items)
if exact_items is not None:
min_items = exact_items
max_items = exact_items
self.items = items
self.additional_items = additional_items
self.min_items = min_items
self.max_items = max_items
self.unique_items = unique_items
def serialize(self, obj: typing.Any) -> typing.Any:
if obj is None:
return None
if isinstance(self.items, list):
return [
serializer.serialize(value)
for serializer, value in zip(self.items, obj)
]
if self.items is None:
return obj
return [self.items.serialize(value) for value in obj] | true | 2 |
829 | typesystem | typesystem.fields | Union | validate | def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
candidate_errors = []
for child in self.any_of:
validated, error = child.validate_or_error(value, strict=strict)
if error is None:
return validated
else:
# If a child returned anything other than a type error, then
# it is a candidate for returning as the primary error.
messages = error.messages()
if (
len(messages) != 1
or messages[0].code != "type"
or messages[0].index
):
candidate_errors.append(error)
if len(candidate_errors) == 1:
# If exactly one child was of the correct type, then we can use
# the error from the child.
raise candidate_errors[0]
raise self.validation_error("union") | [
706,
732
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Union(Field):
errors = {"null": "May not be null.", "union": "Did not match any valid type."}
def __init__(self, any_of: typing.List[Field], **kwargs: typing.Any):
super().__init__(**kwargs)
self.any_of = any_of
if any([child.allow_null for child in any_of]):
self.allow_null = True
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any:
if value is None and self.allow_null:
return None
elif value is None:
raise self.validation_error("null")
candidate_errors = []
for child in self.any_of:
validated, error = child.validate_or_error(value, strict=strict)
if error is None:
return validated
else:
# If a child returned anything other than a type error, then
# it is a candidate for returning as the primary error.
messages = error.messages()
if (
len(messages) != 1
or messages[0].code != "type"
or messages[0].index
):
candidate_errors.append(error)
if len(candidate_errors) == 1:
# If exactly one child was of the correct type, then we can use
# the error from the child.
raise candidate_errors[0]
raise self.validation_error("union") | true | 2 |
830 | typesystem | typesystem.fields | Const | __init__ | def __init__(self, const: typing.Any, **kwargs: typing.Any):
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.const = const | [
751,
754
] | false | [
"NO_DEFAULT",
"FORMATS"
] | import decimal
import re
import typing
from math import isfinite
from typesystem import formats
from typesystem.base import Message, ValidationError, ValidationResult
from typesystem.unique import Uniqueness
NO_DEFAULT = object()
FORMATS = {
"date": formats.DateFormat(),
"time": formats.TimeFormat(),
"datetime": formats.DateTimeFormat(),
"uuid": formats.UUIDFormat(),
}
class Const(Field):
errors = {"only_null": "Must be null.", "const": "Must be the value '{const}'."}
def __init__(self, const: typing.Any, **kwargs: typing.Any):
assert "allow_null" not in kwargs
super().__init__(**kwargs)
self.const = const | false | 0 |
831 | typesystem | typesystem.formats | DateFormat | validate | def validate(self, value: typing.Any) -> datetime.date:
match = DATE_REGEX.match(value)
if not match:
raise self.validation_error("format")
kwargs = {k: int(v) for k, v in match.groupdict().items()}
try:
return datetime.date(**kwargs)
except ValueError:
raise self.validation_error("invalid") | [
52,
61
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class DateFormat(BaseFormat):
errors = {
"format": "Must be a valid date format.",
"invalid": "Must be a real date.",
}
def validate(self, value: typing.Any) -> datetime.date:
match = DATE_REGEX.match(value)
if not match:
raise self.validation_error("format")
kwargs = {k: int(v) for k, v in match.groupdict().items()}
try:
return datetime.date(**kwargs)
except ValueError:
raise self.validation_error("invalid") | true | 2 |
832 | typesystem | typesystem.formats | DateFormat | serialize | def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.date)
return obj.isoformat() | [
63,
69
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class DateFormat(BaseFormat):
errors = {
"format": "Must be a valid date format.",
"invalid": "Must be a real date.",
}
def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.date)
return obj.isoformat() | true | 2 |
833 | typesystem | typesystem.formats | TimeFormat | validate | def validate(self, value: typing.Any) -> datetime.time:
match = TIME_REGEX.match(value)
if not match:
raise self.validation_error("format")
groups = match.groupdict()
if groups["microsecond"]:
groups["microsecond"] = groups["microsecond"].ljust(6, "0")
kwargs = {k: int(v) for k, v in groups.items() if v is not None}
try:
return datetime.time(tzinfo=None, **kwargs)
except ValueError:
raise self.validation_error("invalid") | [
81,
94
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class TimeFormat(BaseFormat):
errors = {
"format": "Must be a valid time format.",
"invalid": "Must be a real time.",
}
def validate(self, value: typing.Any) -> datetime.time:
match = TIME_REGEX.match(value)
if not match:
raise self.validation_error("format")
groups = match.groupdict()
if groups["microsecond"]:
groups["microsecond"] = groups["microsecond"].ljust(6, "0")
kwargs = {k: int(v) for k, v in groups.items() if v is not None}
try:
return datetime.time(tzinfo=None, **kwargs)
except ValueError:
raise self.validation_error("invalid") | true | 2 |
834 | typesystem | typesystem.formats | TimeFormat | serialize | def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.time)
return obj.isoformat() | [
96,
102
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class TimeFormat(BaseFormat):
errors = {
"format": "Must be a valid time format.",
"invalid": "Must be a real time.",
}
def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.time)
return obj.isoformat() | true | 2 |
835 | typesystem | typesystem.formats | DateTimeFormat | validate | def validate(self, value: typing.Any) -> datetime.datetime:
match = DATETIME_REGEX.match(value)
if not match:
raise self.validation_error("format")
groups = match.groupdict()
if groups["microsecond"]:
groups["microsecond"] = groups["microsecond"].ljust(6, "0")
tzinfo_str = groups.pop("tzinfo")
if tzinfo_str == "Z":
tzinfo = datetime.timezone.utc
elif tzinfo_str is not None:
offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0
offset_hours = int(tzinfo_str[1:3])
delta = datetime.timedelta(hours=offset_hours, minutes=offset_mins)
if tzinfo_str[0] == "-":
delta = -delta
tzinfo = datetime.timezone(delta)
else:
tzinfo = None
kwargs = {k: int(v) for k, v in groups.items() if v is not None}
try:
return datetime.datetime(**kwargs, tzinfo=tzinfo) # type: ignore
except ValueError:
raise self.validation_error("invalid") | [
114,
140
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class DateTimeFormat(BaseFormat):
errors = {
"format": "Must be a valid datetime format.",
"invalid": "Must be a real datetime.",
}
def validate(self, value: typing.Any) -> datetime.datetime:
match = DATETIME_REGEX.match(value)
if not match:
raise self.validation_error("format")
groups = match.groupdict()
if groups["microsecond"]:
groups["microsecond"] = groups["microsecond"].ljust(6, "0")
tzinfo_str = groups.pop("tzinfo")
if tzinfo_str == "Z":
tzinfo = datetime.timezone.utc
elif tzinfo_str is not None:
offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0
offset_hours = int(tzinfo_str[1:3])
delta = datetime.timedelta(hours=offset_hours, minutes=offset_mins)
if tzinfo_str[0] == "-":
delta = -delta
tzinfo = datetime.timezone(delta)
else:
tzinfo = None
kwargs = {k: int(v) for k, v in groups.items() if v is not None}
try:
return datetime.datetime(**kwargs, tzinfo=tzinfo) # type: ignore
except ValueError:
raise self.validation_error("invalid") | true | 2 |
836 | typesystem | typesystem.formats | DateTimeFormat | serialize | def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.datetime)
value = obj.isoformat()
if value.endswith("+00:00"):
value = value[:-6] + "Z"
return value | [
142,
153
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class DateTimeFormat(BaseFormat):
errors = {
"format": "Must be a valid datetime format.",
"invalid": "Must be a real datetime.",
}
def serialize(self, obj: typing.Any) -> typing.Union[str, None]:
if obj is None:
return None
assert isinstance(obj, datetime.datetime)
value = obj.isoformat()
if value.endswith("+00:00"):
value = value[:-6] + "Z"
return value | true | 2 |
837 | typesystem | typesystem.formats | UUIDFormat | validate | def validate(self, value: typing.Any) -> uuid.UUID:
match = UUID_REGEX.match(value)
if not match:
raise self.validation_error("format")
return uuid.UUID(value) | [
162,
167
] | false | [
"DATE_REGEX",
"TIME_REGEX",
"DATETIME_REGEX",
"UUID_REGEX"
] | import datetime
import re
import typing
import uuid
from typesystem.base import ValidationError
DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
TIME_REGEX = re.compile(
r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
)
DATETIME_REGEX = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
)
UUID_REGEX = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
)
class UUIDFormat(BaseFormat):
errors = {"format": "Must be valid UUID format."}
def validate(self, value: typing.Any) -> uuid.UUID:
match = UUID_REGEX.match(value)
if not match:
raise self.validation_error("format")
return uuid.UUID(value) | true | 2 |
838 | typesystem | typesystem.json_schema | from_json_schema | def from_json_schema(
data: typing.Union[bool, dict], definitions: SchemaDefinitions = None
) -> Field:
if isinstance(data, bool):
return {True: Any(), False: NeverMatch()}[data]
if definitions is None:
definitions = SchemaDefinitions()
for key, value in data.get("definitions", {}).items():
ref = f"#/definitions/{key}"
definitions[ref] = from_json_schema(value, definitions=definitions)
if "$ref" in data:
return ref_from_json_schema(data, definitions=definitions)
constraints = [] # typing.List[Field]
if any([property_name in data for property_name in TYPE_CONSTRAINTS]):
constraints.append(type_from_json_schema(data, definitions=definitions))
if "enum" in data:
constraints.append(enum_from_json_schema(data, definitions=definitions))
if "const" in data:
constraints.append(const_from_json_schema(data, definitions=definitions))
if "allOf" in data:
constraints.append(all_of_from_json_schema(data, definitions=definitions))
if "anyOf" in data:
constraints.append(any_of_from_json_schema(data, definitions=definitions))
if "oneOf" in data:
constraints.append(one_of_from_json_schema(data, definitions=definitions))
if "not" in data:
constraints.append(not_from_json_schema(data, definitions=definitions))
if "if" in data:
constraints.append(if_then_else_from_json_schema(data, definitions=definitions))
if len(constraints) == 1:
return constraints[0]
elif len(constraints) > 1:
return AllOf(constraints)
return Any() | [
109,
146
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def from_json_schema(
data: typing.Union[bool, dict], definitions: SchemaDefinitions = None
) -> Field:
if isinstance(data, bool):
return {True: Any(), False: NeverMatch()}[data]
if definitions is None:
definitions = SchemaDefinitions()
for key, value in data.get("definitions", {}).items():
ref = f"#/definitions/{key}"
definitions[ref] = from_json_schema(value, definitions=definitions)
if "$ref" in data:
return ref_from_json_schema(data, definitions=definitions)
constraints = [] # typing.List[Field]
if any([property_name in data for property_name in TYPE_CONSTRAINTS]):
constraints.append(type_from_json_schema(data, definitions=definitions))
if "enum" in data:
constraints.append(enum_from_json_schema(data, definitions=definitions))
if "const" in data:
constraints.append(const_from_json_schema(data, definitions=definitions))
if "allOf" in data:
constraints.append(all_of_from_json_schema(data, definitions=definitions))
if "anyOf" in data:
constraints.append(any_of_from_json_schema(data, definitions=definitions))
if "oneOf" in data:
constraints.append(one_of_from_json_schema(data, definitions=definitions))
if "not" in data:
constraints.append(not_from_json_schema(data, definitions=definitions))
if "if" in data:
constraints.append(if_then_else_from_json_schema(data, definitions=definitions))
if len(constraints) == 1:
return constraints[0]
elif len(constraints) > 1:
return AllOf(constraints)
return Any() | true | 2 | |
839 | typesystem | typesystem.json_schema | type_from_json_schema | def type_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
"""
Build a typed field or union of typed fields from a JSON schema object.
"""
type_strings, allow_null = get_valid_types(data)
if len(type_strings) > 1:
items = [
from_json_schema_type(
data, type_string=type_string, allow_null=False, definitions=definitions
)
for type_string in type_strings
]
return Union(any_of=items, allow_null=allow_null)
if len(type_strings) == 0:
return {True: Const(None), False: NeverMatch()}[allow_null]
type_string = type_strings.pop()
return from_json_schema_type(
data, type_string=type_string, allow_null=allow_null, definitions=definitions
) | [
149,
168
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def type_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
"""
Build a typed field or union of typed fields from a JSON schema object.
"""
type_strings, allow_null = get_valid_types(data)
if len(type_strings) > 1:
items = [
from_json_schema_type(
data, type_string=type_string, allow_null=False, definitions=definitions
)
for type_string in type_strings
]
return Union(any_of=items, allow_null=allow_null)
if len(type_strings) == 0:
return {True: Const(None), False: NeverMatch()}[allow_null]
type_string = type_strings.pop()
return from_json_schema_type(
data, type_string=type_string, allow_null=allow_null, definitions=definitions
) | true | 2 | |
840 | typesystem | typesystem.json_schema | get_valid_types | def get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]:
"""
Returns a two-tuple of `(type_strings, allow_null)`.
"""
type_strings = data.get("type", [])
if isinstance(type_strings, str):
type_strings = {type_strings}
else:
type_strings = set(type_strings)
if not type_strings:
type_strings = {"null", "boolean", "object", "array", "number", "string"}
if "number" in type_strings:
type_strings.discard("integer")
allow_null = False
if "null" in type_strings:
allow_null = True
type_strings.remove("null")
return (type_strings, allow_null) | [
173,
195
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]:
"""
Returns a two-tuple of `(type_strings, allow_null)`.
"""
type_strings = data.get("type", [])
if isinstance(type_strings, str):
type_strings = {type_strings}
else:
type_strings = set(type_strings)
if not type_strings:
type_strings = {"null", "boolean", "object", "array", "number", "string"}
if "number" in type_strings:
type_strings.discard("integer")
allow_null = False
if "null" in type_strings:
allow_null = True
type_strings.remove("null")
return (type_strings, allow_null) | true | 2 | |
841 | typesystem | typesystem.json_schema | from_json_schema_type | def from_json_schema_type(
data: dict, type_string: str, allow_null: bool, definitions: SchemaDefinitions
) -> Field:
"""
Build a typed field from a JSON schema object.
"""
if type_string == "number":
kwargs = {
"allow_null": allow_null,
"minimum": data.get("minimum", None),
"maximum": data.get("maximum", None),
"exclusive_minimum": data.get("exclusiveMinimum", None),
"exclusive_maximum": data.get("exclusiveMaximum", None),
"multiple_of": data.get("multipleOf", None),
"default": data.get("default", NO_DEFAULT),
}
return Float(**kwargs)
elif type_string == "integer":
kwargs = {
"allow_null": allow_null,
"minimum": data.get("minimum", None),
"maximum": data.get("maximum", None),
"exclusive_minimum": data.get("exclusiveMinimum", None),
"exclusive_maximum": data.get("exclusiveMaximum", None),
"multiple_of": data.get("multipleOf", None),
"default": data.get("default", NO_DEFAULT),
}
return Integer(**kwargs)
elif type_string == "string":
min_length = data.get("minLength", 0)
kwargs = {
"allow_null": allow_null,
"allow_blank": min_length == 0,
"min_length": min_length if min_length > 1 else None,
"max_length": data.get("maxLength", None),
"format": data.get("format"),
"pattern": data.get("pattern", None),
"default": data.get("default", NO_DEFAULT),
}
return String(**kwargs)
elif type_string == "boolean":
kwargs = {"allow_null": allow_null, "default": data.get("default", NO_DEFAULT)}
return Boolean(**kwargs)
elif type_string == "array":
items = data.get("items", None)
if items is None:
items_argument: typing.Union[None, Field, typing.List[Field]] = None
elif isinstance(items, list):
items_argument = [
from_json_schema(item, definitions=definitions) for item in items
]
else:
items_argument = from_json_schema(items, definitions=definitions)
additional_items = data.get("additionalItems", None)
if additional_items is None:
additional_items_argument: typing.Union[bool, Field] = True
elif isinstance(additional_items, bool):
additional_items_argument = additional_items
else:
additional_items_argument = from_json_schema(
additional_items, definitions=definitions
)
kwargs = {
"allow_null": allow_null,
"min_items": data.get("minItems", 0),
"max_items": data.get("maxItems", None),
"additional_items": additional_items_argument,
"items": items_argument,
"unique_items": data.get("uniqueItems", False),
"default": data.get("default", NO_DEFAULT),
}
return Array(**kwargs)
elif type_string == "object":
properties = data.get("properties", None)
if properties is None:
properties_argument: typing.Optional[typing.Dict[str, Field]] = None
else:
properties_argument = {
key: from_json_schema(value, definitions=definitions)
for key, value in properties.items()
}
pattern_properties = data.get("patternProperties", None)
if pattern_properties is None:
pattern_properties_argument: typing.Optional[typing.Dict[str, Field]] = (
None
)
else:
pattern_properties_argument = {
key: from_json_schema(value, definitions=definitions)
for key, value in pattern_properties.items()
}
additional_properties = data.get("additionalProperties", None)
if additional_properties is None:
additional_properties_argument: typing.Union[None, bool, Field] = (None)
elif isinstance(additional_properties, bool):
additional_properties_argument = additional_properties
else:
additional_properties_argument = from_json_schema(
additional_properties, definitions=definitions
)
property_names = data.get("propertyNames", None)
if property_names is None:
property_names_argument: typing.Optional[Field] = None
else:
property_names_argument = from_json_schema(
property_names, definitions=definitions
)
kwargs = {
"allow_null": allow_null,
"properties": properties_argument,
"pattern_properties": pattern_properties_argument,
"additional_properties": additional_properties_argument,
"property_names": property_names_argument,
"min_properties": data.get("minProperties", None),
"max_properties": data.get("maxProperties", None),
"required": data.get("required", None),
"default": data.get("default", NO_DEFAULT),
}
return Object(**kwargs)
assert False, f"Invalid argument type_string={type_string!r}" | [
198,
328
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def from_json_schema_type(
data: dict, type_string: str, allow_null: bool, definitions: SchemaDefinitions
) -> Field:
"""
Build a typed field from a JSON schema object.
"""
if type_string == "number":
kwargs = {
"allow_null": allow_null,
"minimum": data.get("minimum", None),
"maximum": data.get("maximum", None),
"exclusive_minimum": data.get("exclusiveMinimum", None),
"exclusive_maximum": data.get("exclusiveMaximum", None),
"multiple_of": data.get("multipleOf", None),
"default": data.get("default", NO_DEFAULT),
}
return Float(**kwargs)
elif type_string == "integer":
kwargs = {
"allow_null": allow_null,
"minimum": data.get("minimum", None),
"maximum": data.get("maximum", None),
"exclusive_minimum": data.get("exclusiveMinimum", None),
"exclusive_maximum": data.get("exclusiveMaximum", None),
"multiple_of": data.get("multipleOf", None),
"default": data.get("default", NO_DEFAULT),
}
return Integer(**kwargs)
elif type_string == "string":
min_length = data.get("minLength", 0)
kwargs = {
"allow_null": allow_null,
"allow_blank": min_length == 0,
"min_length": min_length if min_length > 1 else None,
"max_length": data.get("maxLength", None),
"format": data.get("format"),
"pattern": data.get("pattern", None),
"default": data.get("default", NO_DEFAULT),
}
return String(**kwargs)
elif type_string == "boolean":
kwargs = {"allow_null": allow_null, "default": data.get("default", NO_DEFAULT)}
return Boolean(**kwargs)
elif type_string == "array":
items = data.get("items", None)
if items is None:
items_argument: typing.Union[None, Field, typing.List[Field]] = None
elif isinstance(items, list):
items_argument = [
from_json_schema(item, definitions=definitions) for item in items
]
else:
items_argument = from_json_schema(items, definitions=definitions)
additional_items = data.get("additionalItems", None)
if additional_items is None:
additional_items_argument: typing.Union[bool, Field] = True
elif isinstance(additional_items, bool):
additional_items_argument = additional_items
else:
additional_items_argument = from_json_schema(
additional_items, definitions=definitions
)
kwargs = {
"allow_null": allow_null,
"min_items": data.get("minItems", 0),
"max_items": data.get("maxItems", None),
"additional_items": additional_items_argument,
"items": items_argument,
"unique_items": data.get("uniqueItems", False),
"default": data.get("default", NO_DEFAULT),
}
return Array(**kwargs)
elif type_string == "object":
properties = data.get("properties", None)
if properties is None:
properties_argument: typing.Optional[typing.Dict[str, Field]] = None
else:
properties_argument = {
key: from_json_schema(value, definitions=definitions)
for key, value in properties.items()
}
pattern_properties = data.get("patternProperties", None)
if pattern_properties is None:
pattern_properties_argument: typing.Optional[typing.Dict[str, Field]] = (
None
)
else:
pattern_properties_argument = {
key: from_json_schema(value, definitions=definitions)
for key, value in pattern_properties.items()
}
additional_properties = data.get("additionalProperties", None)
if additional_properties is None:
additional_properties_argument: typing.Union[None, bool, Field] = (None)
elif isinstance(additional_properties, bool):
additional_properties_argument = additional_properties
else:
additional_properties_argument = from_json_schema(
additional_properties, definitions=definitions
)
property_names = data.get("propertyNames", None)
if property_names is None:
property_names_argument: typing.Optional[Field] = None
else:
property_names_argument = from_json_schema(
property_names, definitions=definitions
)
kwargs = {
"allow_null": allow_null,
"properties": properties_argument,
"pattern_properties": pattern_properties_argument,
"additional_properties": additional_properties_argument,
"property_names": property_names_argument,
"min_properties": data.get("minProperties", None),
"max_properties": data.get("maxProperties", None),
"required": data.get("required", None),
"default": data.get("default", NO_DEFAULT),
}
return Object(**kwargs)
assert False, f"Invalid argument type_string={type_string!r}" | true | 2 | |
842 | typesystem | typesystem.json_schema | ref_from_json_schema | def ref_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
reference_string = data["$ref"]
assert reference_string.startswith("#/"), "Unsupported $ref style in document."
return Reference(to=reference_string, definitions=definitions) | [
333,
336
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def ref_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
reference_string = data["$ref"]
assert reference_string.startswith("#/"), "Unsupported $ref style in document."
return Reference(to=reference_string, definitions=definitions) | false | 0 | |
843 | typesystem | typesystem.json_schema | enum_from_json_schema | def enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
choices = [(item, item) for item in data["enum"]]
kwargs = {"choices": choices, "default": data.get("default", NO_DEFAULT)}
return Choice(**kwargs) | [
339,
342
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
choices = [(item, item) for item in data["enum"]]
kwargs = {"choices": choices, "default": data.get("default", NO_DEFAULT)}
return Choice(**kwargs) | false | 0 | |
844 | typesystem | typesystem.json_schema | const_from_json_schema | def const_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
const = data["const"]
kwargs = {"const": const, "default": data.get("default", NO_DEFAULT)}
return Const(**kwargs) | [
345,
348
] | false | [
"TYPE_CONSTRAINTS",
"definitions",
"JSONSchema"
] | import re
import typing
from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf
from typesystem.fields import (
NO_DEFAULT,
Any,
Array,
Boolean,
Choice,
Const,
Decimal,
Field,
Float,
Integer,
Number,
Object,
String,
Union,
)
from typesystem.schemas import Reference, Schema, SchemaDefinitions
TYPE_CONSTRAINTS = {
"additionalItems",
"additionalProperties",
"boolean_schema",
"contains",
"dependencies",
"exclusiveMaximum",
"exclusiveMinimum",
"items",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"pattern",
"patternProperties",
"properties",
"propertyNames",
"required",
"type",
"uniqueItems",
}
definitions["JSONSchema"] = JSONSchema
JSONSchema = (
Object(
properties={
"$ref": String(),
"type": String() | Array(items=String()),
"enum": Array(unique_items=True, min_items=1),
"definitions": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
# String
"minLength": Integer(minimum=0),
"maxLength": Integer(minimum=0),
"pattern": String(format="regex"),
"format": String(),
# Numeric
"minimum": Number(),
"maximum": Number(),
"exclusiveMinimum": Number(),
"exclusiveMaximum": Number(),
"multipleOf": Number(exclusive_minimum=0),
# Object
"properties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"minProperties": Integer(minimum=0),
"maxProperties": Integer(minimum=0),
"patternProperties": Object(
additional_properties=Reference("JSONSchema", definitions=definitions)
),
"additionalProperties": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"required": Array(items=String(), unique_items=True),
# Array
"items": (
Reference("JSONSchema", definitions=definitions)
| Array(
items=Reference("JSONSchema", definitions=definitions), min_items=1
)
),
"additionalItems": (
Reference("JSONSchema", definitions=definitions) | Boolean()
),
"minItems": Integer(minimum=0),
"maxItems": Integer(minimum=0),
"uniqueItems": Boolean(),
}
)
| Boolean()
)
def const_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field:
const = data["const"]
kwargs = {"const": const, "default": data.get("default", NO_DEFAULT)}
return Const(**kwargs) | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.