source
stringclasses
1 value
version
stringclasses
1 value
module
stringclasses
43 values
function
stringclasses
307 values
input
stringlengths
3
496
expected
stringlengths
0
40.5k
signature
stringclasses
0 values
cpython
cfcd524
typing
_LazyAnnotationLib._should_unflatten_callable_args
>>> collections.abc.Callable[P, str].__args__ == (P, str)
True As a result, if we need to reconstruct the Callable from its __args__, we need to unflatten it.
null
cpython
cfcd524
typing
_LazyAnnotationLib._collect_type_parameters
>>> P = ParamSpec('P')
null
cpython
cfcd524
typing
_LazyAnnotationLib._collect_type_parameters
>>> T = TypeVar('T')
null
cpython
cfcd524
typing
_LazyAnnotationLib._collect_type_parameters
>>> _collect_type_parameters((T, Callable[P, T]))
(~T, ~P)
null
cpython
cfcd524
typing
_LazyAnnotationLib._collect_type_parameters
>>> _collect_type_parameters((list[T], Generic[P, T]))
(~P, ~T)
null
cpython
cfcd524
typing
Closable.get_origin
>>> P = ParamSpec('P')
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(Literal[42]) is Literal
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(int) is None
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(ClassVar[int]) is ClassVar
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(Generic) is Generic
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(Generic[T]) is Generic
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(Union[T, int]) is Union
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(List[Tuple[T, T]][int]) is list
null
cpython
cfcd524
typing
Closable.get_origin
>>> assert get_origin(P.args) is P
null
cpython
cfcd524
typing
Closable.get_args
>>> T = TypeVar('T')
null
cpython
cfcd524
typing
Closable.get_args
>>> assert get_args(Dict[str, int]) == (str, int)
null
cpython
cfcd524
typing
Closable.get_args
>>> assert get_args(int) == ()
null
cpython
cfcd524
typing
Closable.get_args
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
null
cpython
cfcd524
typing
Closable.get_args
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
null
cpython
cfcd524
typing
Closable.get_args
>>> assert get_args(Callable[[], T][int]) == ([], int)
null
cpython
cfcd524
typing
Closable.is_typeddict
>>> from typing import TypedDict
null
cpython
cfcd524
typing
Closable.is_typeddict
>>> class Film(TypedDict): ... title: str ... year: int ...
null
cpython
cfcd524
typing
Closable.is_typeddict
>>> is_typeddict(Film)
True
null
cpython
cfcd524
typing
Closable.is_typeddict
>>> is_typeddict(dict)
False
null
cpython
cfcd524
typing
_TypedDictMeta.TypedDict
>>> class Point2D(TypedDict): ... x: int ... y: int ... label: str ...
null
cpython
cfcd524
typing
_TypedDictMeta.TypedDict
>>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
null
cpython
cfcd524
typing
_TypedDictMeta.TypedDict
>>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
null
cpython
cfcd524
typing
_TypedDictMeta.TypedDict
>>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
True The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports an additional equivalent form:: Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality:: class Point2D(TypedDict, total=False): x: int y: int This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required. The Required and NotRequired special forms can also be used to mark individual keys as being required or not required:: class Point2D(TypedDict): x: int # the "x" key must always be present (Required is the default) y: NotRequired[int] # the "y" key can be omitted See PEP 655 for more details on Required and NotRequired. The ReadOnly special form can be used to mark individual keys as immutable for type checkers:: class DatabaseUser(TypedDict): id: ReadOnly[int] # the "id" key must not be modified username: str # the "username" key can be changed The closed argument controls whether the TypedDict allows additional non-required items during inheritance and assignability checks. If closed=True, the TypedDict does not allow additional items:: Point2D = TypedDict('Point2D', {'x': int, 'y': int}, closed=True) class Point3D(Point2D): z: int # Type checker error Passing closed=False explicitly requests TypedDict's default open behavior. If closed is not provided, the behavior is inherited from the superclass. A type checker is only expected to support a literal False or True as the value of the closed argument. The extra_items argument can instead be used to specify the assignable type of unknown non-required keys:: Point2D = TypedDict('Point2D', {'x': int, 'y': int}, extra_items=int) class Point3D(Point2D): z: int # OK label: str # Type checker error The extra_items argument is also inherited through subclassing. It is unset by default, and it may not be used with the closed argument at the same time. See PEP 728 for more information about closed and extra_items.
null
cpython
cfcd524
typing
Child.is_protocol
>>> from typing import Protocol, is_protocol
null
cpython
cfcd524
typing
Child.is_protocol
>>> class P(Protocol): ... def a(self) -> str: ... ... b: int
null
cpython
cfcd524
typing
Child.is_protocol
>>> is_protocol(P)
True
null
cpython
cfcd524
typing
Child.is_protocol
>>> is_protocol(int)
False
null
cpython
cfcd524
typing
Child.get_protocol_members
>>> from typing import Protocol, get_protocol_members
null
cpython
cfcd524
typing
Child.get_protocol_members
>>> class P(Protocol): ... def a(self) -> str: ... ... b: int
null
cpython
cfcd524
typing
Child.get_protocol_members
>>> get_protocol_members(P) == frozenset({'a', 'b'})
True Raise a TypeError for arguments that are not Protocols.
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(10, -8)
Fraction(-5, 4)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(Fraction(1, 7), 5)
Fraction(1, 35)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(Fraction(1, 7), Fraction(2, 3))
Fraction(3, 14)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction('314')
Fraction(314, 1)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction('-35/4')
Fraction(-35, 4)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction('3.1415') # conversion from numeric string
Fraction(6283, 2000)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction('-47e-2') # string may include a decimal exponent
Fraction(-47, 100)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(1.47) # direct construction from float (exact conversion)
Fraction(6620291452234629, 4503599627370496)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(2.25)
Fraction(9, 4)
null
cpython
cfcd524
fractions
Fraction.__new__
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
null
cpython
cfcd524
fractions
Fraction.limit_denominator
>>> Fraction('3.141592653589793').limit_denominator(10)
Fraction(22, 7)
null
cpython
cfcd524
fractions
Fraction.limit_denominator
>>> Fraction('3.141592653589793').limit_denominator(100)
Fraction(311, 99)
null
cpython
cfcd524
fractions
Fraction.limit_denominator
>>> Fraction(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
null
cpython
cfcd524
secrets
token_bytes
>>> token_bytes(16) #doctest:+SKIP
b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
null
cpython
cfcd524
secrets
token_hex
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
null
cpython
cfcd524
secrets
token_urlsafe
>>> token_urlsafe(16) #doctest:+SKIP
'Drmhze6EPcv0fN_81Bj-nA'
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> import smtplib
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> s=smtplib.SMTP("localhost")
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> msg = '''\\ ... From: Me@my.org ... Subject: testin'... ... ... This is a test '''
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> s.sendmail("me@my.org",tolist,msg)
{ "three@three.org" : ( 550 ,"User unknown" ) }
null
cpython
cfcd524
smtplib
SMTP.sendmail
>>> s.quit()
In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary.
null
cpython
cfcd524
hashlib
__module__
>>> import hashlib
null
cpython
cfcd524
hashlib
__module__
>>> m = hashlib.sha256()
null
cpython
cfcd524
hashlib
__module__
>>> m.update(b"Nobody inspects")
null
cpython
cfcd524
hashlib
__module__
>>> m.update(b" the spammish repetition")
null
cpython
cfcd524
hashlib
__module__
>>> m.digest() # doctest: +ELLIPSIS
b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7...' More condensed:
null
cpython
cfcd524
hashlib
__module__
>>> hashlib.sha256(b"Nobody inspects the spammish repetition").hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
null
cpython
cfcd524
ftplib
__module__
>>> from ftplib import FTP
null
cpython
cfcd524
ftplib
__module__
>>> ftp = FTP('ftp.python.org') # connect to host, default port
null
cpython
cfcd524
ftplib
__module__
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest login ok, access restrictions apply.'
null
cpython
cfcd524
ftplib
__module__
>>> ftp.retrlines('LIST') # list directory contents
total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.'
null
cpython
cfcd524
ftplib
__module__
>>> ftp.quit()
'221 Goodbye.'
null
cpython
cfcd524
ftplib
__module__
>>>
A nice test that reveals some of the network dialogue would be: python ftplib.py -d localhost -l -p -l
null
cpython
cfcd524
statistics
__module__
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625 Calculate the standard median of discrete data:
null
cpython
cfcd524
statistics
__module__
>>> median([2, 3, 4, 5])
3.5 Calculate the median, or 50th percentile, of data grouped into class intervals centred on the data values provided. E.g. if your data points are rounded to the nearest whole number:
null
cpython
cfcd524
statistics
__module__
>>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
2.8333333333... This should be interpreted in this way: you have two data points in the class interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in the class interval 3.5-4.5. The median of these data points is 2.8333... Calculating variability or spread --------------------------------- ================== ============================================= Function Description ================== ============================================= pvariance Population variance of data. variance Sample variance of data. pstdev Population standard deviation of data. stdev Sample standard deviation of data. ================== ============================================= Calculate the standard deviation of sample data:
null
cpython
cfcd524
statistics
__module__
>>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
4.38961843444... If you have previously calculated the mean, you can pass it as the optional second argument to the four "spread" functions to avoid recalculating it:
null
cpython
cfcd524
statistics
__module__
>>> data = [1, 2, 2, 4, 4, 4, 5, 6]
null
cpython
cfcd524
statistics
__module__
>>> mu = mean(data)
null
cpython
cfcd524
statistics
__module__
>>> pvariance(data, mu)
2.5 Statistics for relations between two inputs ------------------------------------------- ================== ==================================================== Function Description ================== ==================================================== covariance Sample covariance for two variables. correlation Pearson's correlation coefficient for two variables. linear_regression Intercept and slope for simple linear regression. ================== ==================================================== Calculate covariance, Pearson's correlation, and simple linear regression for two inputs:
null
cpython
cfcd524
statistics
__module__
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
null
cpython
cfcd524
statistics
__module__
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
null
cpython
cfcd524
statistics
__module__
>>> covariance(x, y)
0.75
null
cpython
cfcd524
statistics
__module__
>>> correlation(x, y) #doctest: +ELLIPSIS
0.31622776601...
null
cpython
cfcd524
statistics
__module__
>>> linear_regression(x, y) #doctest:
LinearRegression(slope=0.1, intercept=1.5) Exceptions ---------- A single exception is defined: StatisticsError is a subclass of ValueError.
null
cpython
cfcd524
statistics
StatisticsError.mean
>>> mean([1, 2, 3, 4, 4])
2.8
null
cpython
cfcd524
statistics
StatisticsError.mean
>>> from fractions import Fraction as F
null
cpython
cfcd524
statistics
StatisticsError.mean
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
null
cpython
cfcd524
statistics
StatisticsError.mean
>>> from decimal import Decimal as D
null
cpython
cfcd524
statistics
StatisticsError.mean
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625') If ``data`` is empty, StatisticsError will be raised.
null
cpython
cfcd524
statistics
StatisticsError.fmean
>>> fmean([3.5, 4.0, 5.25])
4.25
null
cpython
cfcd524
statistics
StatisticsError.geometric_mean
>>> round(geometric_mean([54, 24, 36]), 9)
36.0
null
cpython
cfcd524
statistics
StatisticsError.harmonic_mean
>>> harmonic_mean([40, 60])
48.0 Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up to 60 km/hr for the remaining 30 km of the journey. What is the average speed?
null
cpython
cfcd524
statistics
StatisticsError.harmonic_mean
>>> harmonic_mean([40, 60], weights=[5, 30])
56.0 If ``data`` is empty, or any element is less than zero, ``harmonic_mean`` will raise ``StatisticsError``.
null
cpython
cfcd524
statistics
StatisticsError.median
>>> median([1, 3, 5])
3
null
cpython
cfcd524
statistics
StatisticsError.median
>>> median([1, 3, 5, 7])
4.0
null
cpython
cfcd524
statistics
StatisticsError.median_low
>>> median_low([1, 3, 5])
3
null
cpython
cfcd524
statistics
StatisticsError.median_low
>>> median_low([1, 3, 5, 7])
3
null
cpython
cfcd524
statistics
StatisticsError.median_high
>>> median_high([1, 3, 5])
3
null
cpython
cfcd524
statistics
StatisticsError.median_high
>>> median_high([1, 3, 5, 7])
5
null
cpython
cfcd524
statistics
StatisticsError.median_grouped
>>> demographics = Counter({ ... 25: 172, # 20 to 30 years old ... 35: 484, # 30 to 40 years old ... 45: 387, # 40 to 50 years old ... 55: 22, # 50 to 60 years old ... 65: 6, # 60 to 70 years old ... })
The 50th percentile (median) is the 536th person out of the 1071 member cohort. That person is in the 30 to 40 year old age group. The regular median() function would assume that everyone in the tricenarian age group was exactly 35 years old. A more tenable assumption is that the 484 members of that age group are evenly distributed between 30 and 40. For that, we use median_grouped().
null
cpython
cfcd524
statistics
StatisticsError.median_grouped
>>> data = list(demographics.elements())
null
cpython
cfcd524
statistics
StatisticsError.median_grouped
>>> median(data)
35
null
cpython
cfcd524
statistics
StatisticsError.median_grouped
>>> round(median_grouped(data, interval=10), 1)
37.5 The caller is responsible for making sure the data points are separated by exact multiples of *interval*. This is essential for getting a correct result. The function does not check this precondition. Inputs may be any numeric type that can be coerced to a float during the interpolation step.
null