language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | ipython__ipython | tests/test_handlers.py | {
"start": 626,
"end": 772
} | class ____(object):
def __getitem__(self, idx):
return True
def __call__(self, *args, **kws):
return True
| CallableIndexable |
python | TheAlgorithms__Python | data_structures/stacks/stack_using_two_queues.py | {
"start": 120,
"end": 2251
} | class ____:
"""
https://www.geeksforgeeks.org/implement-stack-using-queue/
>>> stack = StackWithQueues()
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.peek()
3
>>> stack.pop()
3
>>> stack.peek()
2
>>> stack.pop()
2
>>> stack.pop()
1
>>> stack.peek() is None
True
>>> stack.pop()
Traceback (most recent call last):
...
IndexError: pop from an empty deque
"""
main_queue: deque[int] = field(default_factory=deque)
temp_queue: deque[int] = field(default_factory=deque)
def push(self, item: int) -> None:
self.temp_queue.append(item)
while self.main_queue:
self.temp_queue.append(self.main_queue.popleft())
self.main_queue, self.temp_queue = self.temp_queue, self.main_queue
def pop(self) -> int:
return self.main_queue.popleft()
def peek(self) -> int | None:
return self.main_queue[0] if self.main_queue else None
if __name__ == "__main__":
import doctest
doctest.testmod()
stack: StackWithQueues | None = StackWithQueues()
while stack:
print("\nChoose operation:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Quit")
choice = input("Enter choice (1/2/3/4): ")
if choice == "1":
element = int(input("Enter an integer to push: ").strip())
stack.push(element)
print(f"{element} pushed onto the stack.")
elif choice == "2":
popped_element = stack.pop()
if popped_element is not None:
print(f"Popped element: {popped_element}")
else:
print("Stack is empty.")
elif choice == "3":
peeked_element = stack.peek()
if peeked_element is not None:
print(f"Top element: {peeked_element}")
else:
print("Stack is empty.")
elif choice == "4":
del stack
stack = None
else:
print("Invalid choice. Please try again.")
| StackWithQueues |
python | numpy__numpy | numpy/ma/tests/test_core.py | {
"start": 167962,
"end": 194464
} | class ____:
# Test class for miscellaneous functions.
def test_masked_where_bool(self):
x = [1, 2]
y = masked_where(False, x)
assert_equal(y, [1, 2])
assert_equal(y[1], 2)
def test_masked_equal_wlist(self):
x = [1, 2, 3]
mx = masked_equal(x, 3)
assert_equal(mx, x)
assert_equal(mx._mask, [0, 0, 1])
mx = masked_not_equal(x, 3)
assert_equal(mx, x)
assert_equal(mx._mask, [1, 1, 0])
def test_masked_equal_fill_value(self):
x = [1, 2, 3]
mx = masked_equal(x, 3)
assert_equal(mx._mask, [0, 0, 1])
assert_equal(mx.fill_value, 3)
def test_masked_where_condition(self):
# Tests masking functions.
x = array([1., 2., 3., 4., 5.])
x[2] = masked
assert_equal(masked_where(greater(x, 2), x), masked_greater(x, 2))
assert_equal(masked_where(greater_equal(x, 2), x),
masked_greater_equal(x, 2))
assert_equal(masked_where(less(x, 2), x), masked_less(x, 2))
assert_equal(masked_where(less_equal(x, 2), x),
masked_less_equal(x, 2))
assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
assert_equal(masked_where(equal(x, 2), x), masked_equal(x, 2))
assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
assert_equal(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
[99, 99, 3, 4, 5])
def test_masked_where_oddities(self):
# Tests some generic features.
atest = ones((10, 10, 10), dtype=float)
btest = zeros(atest.shape, MaskType)
ctest = masked_where(btest, atest)
assert_equal(atest, ctest)
def test_masked_where_shape_constraint(self):
a = arange(10)
with assert_raises(IndexError):
masked_equal(1, a)
test = masked_equal(a, 1)
assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
def test_masked_where_structured(self):
# test that masked_where on a structured array sets a structured
# mask (see issue #2972)
a = np.zeros(10, dtype=[("A", "<f2"), ("B", "<f4")])
with np.errstate(over="ignore"):
# NOTE: The float16 "uses" 1e20 as mask, which overflows to inf
# and warns. Unrelated to this test, but probably undesired.
# But NumPy previously did not warn for this overflow.
am = np.ma.masked_where(a["A"] < 5, a)
assert_equal(am.mask.dtype.names, am.dtype.names)
assert_equal(am["A"],
np.ma.masked_array(np.zeros(10), np.ones(10)))
def test_masked_where_mismatch(self):
# gh-4520
x = np.arange(10)
y = np.arange(5)
assert_raises(IndexError, np.ma.masked_where, y > 6, x)
def test_masked_otherfunctions(self):
assert_equal(masked_inside(list(range(5)), 1, 3),
[0, 199, 199, 199, 4])
assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])
assert_equal(masked_inside(array(list(range(5)),
mask=[1, 0, 0, 0, 0]), 1, 3).mask,
[1, 1, 1, 1, 0])
assert_equal(masked_outside(array(list(range(5)),
mask=[0, 1, 0, 0, 0]), 1, 3).mask,
[1, 1, 0, 0, 1])
assert_equal(masked_equal(array(list(range(5)),
mask=[1, 0, 0, 0, 0]), 2).mask,
[1, 0, 1, 0, 0])
assert_equal(masked_not_equal(array([2, 2, 1, 2, 1],
mask=[1, 0, 0, 0, 0]), 2).mask,
[1, 0, 1, 0, 1])
def test_round(self):
a = array([1.23456, 2.34567, 3.45678, 4.56789, 5.67890],
mask=[0, 1, 0, 0, 0])
assert_equal(a.round(), [1., 2., 3., 5., 6.])
assert_equal(a.round(1), [1.2, 2.3, 3.5, 4.6, 5.7])
assert_equal(a.round(3), [1.235, 2.346, 3.457, 4.568, 5.679])
b = empty_like(a)
a.round(out=b)
assert_equal(b, [1., 2., 3., 5., 6.])
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
def test_round_with_output(self):
# Testing round with an explicit output
xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
xm[:, 0] = xm[0] = xm[-1, -1] = masked
# A ndarray as explicit input
output = np.empty((3, 4), dtype=float)
output.fill(-9999)
result = np.round(xm, decimals=2, out=output)
# ... the result should be the given output
assert_(result is output)
assert_equal(result, xm.round(decimals=2, out=output))
output = empty((3, 4), dtype=float)
result = xm.round(decimals=2, out=output)
assert_(result is output)
def test_round_with_scalar(self):
# Testing round with scalar/zero dimension input
# GH issue 2244
a = array(1.1, mask=[False])
assert_equal(a.round(), 1)
a = array(1.1, mask=[True])
assert_(a.round() is masked)
a = array(1.1, mask=[False])
output = np.empty(1, dtype=float)
output.fill(-9999)
a.round(out=output)
assert_equal(output, 1)
a = array(1.1, mask=[False])
output = array(-9999., mask=[True])
a.round(out=output)
assert_equal(output[()], 1)
a = array(1.1, mask=[True])
output = array(-9999., mask=[False])
a.round(out=output)
assert_(output[()] is masked)
def test_identity(self):
a = identity(5)
assert_(isinstance(a, MaskedArray))
assert_equal(a, np.identity(5))
def test_power(self):
x = -1.1
assert_almost_equal(power(x, 2.), 1.21)
assert_(power(x, masked) is masked)
x = array([-1.1, -1.1, 1.1, 1.1, 0.])
b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
y = power(x, b)
assert_almost_equal(y, [0, 1.21, 1.04880884817, 1.21, 0.])
assert_equal(y._mask, [1, 0, 0, 0, 1])
b.mask = nomask
y = power(x, b)
assert_equal(y._mask, [1, 0, 0, 0, 1])
z = x ** b
assert_equal(z._mask, y._mask)
assert_almost_equal(z, y)
assert_almost_equal(z._data, y._data)
x **= b
assert_equal(x._mask, y._mask)
assert_almost_equal(x, y)
assert_almost_equal(x._data, y._data)
def test_power_with_broadcasting(self):
# Test power w/ broadcasting
a2 = np.array([[1., 2., 3.], [4., 5., 6.]])
a2m = array(a2, mask=[[1, 0, 0], [0, 0, 1]])
b1 = np.array([2, 4, 3])
b2 = np.array([b1, b1])
b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]])
ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]],
mask=[[1, 1, 0], [0, 1, 1]])
# No broadcasting, base & exp w/ mask
test = a2m ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
# No broadcasting, base w/ mask, exp w/o mask
test = a2m ** b2
assert_equal(test, ctrl)
assert_equal(test.mask, a2m.mask)
# No broadcasting, base w/o mask, exp w/ mask
test = a2 ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, b2m.mask)
ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]],
mask=[[0, 1, 0], [0, 1, 0]])
test = b1 ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
test = b2m ** b1
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
def test_where(self):
# Test the where function
x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
xm.set_fill_value(1e+20)
d = where(xm > 2, xm, -9)
assert_equal(d, [-9., -9., -9., -9., -9., 4.,
-9., -9., 10., -9., -9., 3.])
assert_equal(d._mask, xm._mask)
d = where(xm > 2, -9, ym)
assert_equal(d, [5., 0., 3., 2., -1., -9.,
-9., -10., -9., 1., 0., -9.])
assert_equal(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0])
d = where(xm > 2, xm, masked)
assert_equal(d, [-9., -9., -9., -9., -9., 4.,
-9., -9., 10., -9., -9., 3.])
tmp = xm._mask.copy()
tmp[(xm <= 2).filled(True)] = True
assert_equal(d._mask, tmp)
with np.errstate(invalid="warn"):
# The fill value is 1e20, it cannot be converted to `int`:
with pytest.warns(RuntimeWarning, match="invalid value"):
ixm = xm.astype(int)
d = where(ixm > 2, ixm, masked)
assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3])
assert_equal(d.dtype, ixm.dtype)
def test_where_object(self):
a = np.array(None)
b = masked_array(None)
r = b.copy()
assert_equal(np.ma.where(True, a, a), r)
assert_equal(np.ma.where(True, b, b), r)
def test_where_with_masked_choice(self):
x = arange(10)
x[3] = masked
c = x >= 8
# Set False to masked
z = where(c, x, masked)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is masked)
assert_(z[7] is masked)
assert_(z[8] is not masked)
assert_(z[9] is not masked)
assert_equal(x, z)
# Set True to masked
z = where(c, masked, x)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is not masked)
assert_(z[7] is not masked)
assert_(z[8] is masked)
assert_(z[9] is masked)
def test_where_with_masked_condition(self):
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
x = arange(1, 6)
x[-1] = masked
y = arange(1, 6) * 10
y[2] = masked
c = array([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0])
cm = c.filled(1)
z = where(c, x, y)
zm = where(cm, x, y)
assert_equal(z, zm)
assert_(getmask(zm) is nomask)
assert_equal(zm, [1, 2, 3, 40, 50])
z = where(c, masked, 1)
assert_equal(z, [99, 99, 99, 1, 1])
z = where(c, 1, masked)
assert_equal(z, [99, 1, 1, 99, 99])
def test_where_type(self):
# Test the type conservation with where
x = np.arange(4, dtype=np.int32)
y = np.arange(4, dtype=np.float32) * 2.2
test = where(x > 1.5, y, x).dtype
control = np.result_type(np.int32, np.float32)
assert_equal(test, control)
def test_where_broadcast(self):
# Issue 8599
x = np.arange(9).reshape(3, 3)
y = np.zeros(3)
core = np.where([1, 0, 1], x, y)
ma = where([1, 0, 1], x, y)
assert_equal(core, ma)
assert_equal(core.dtype, ma.dtype)
def test_where_structured(self):
# Issue 8600
dt = np.dtype([('a', int), ('b', int)])
x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
y = np.array((10, 20), dtype=dt)
core = np.where([0, 1, 1], x, y)
ma = np.where([0, 1, 1], x, y)
assert_equal(core, ma)
assert_equal(core.dtype, ma.dtype)
def test_where_structured_masked(self):
dt = np.dtype([('a', int), ('b', int)])
x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
ma = where([0, 1, 1], x, masked)
expected = masked_where([1, 0, 0], x)
assert_equal(ma.dtype, expected.dtype)
assert_equal(ma, expected)
assert_equal(ma.mask, expected.mask)
def test_masked_invalid_error(self):
a = np.arange(5, dtype=object)
a[3] = np.inf
a[2] = np.nan
with pytest.raises(TypeError,
match="not supported for the input types"):
np.ma.masked_invalid(a)
def test_masked_invalid_pandas(self):
# getdata() used to be bad for pandas series due to its _data
# attribute. This test is a regression test mainly and may be
# removed if getdata() is adjusted.
class Series:
_data = "nonsense"
def __array__(self, dtype=None, copy=None):
return np.array([5, np.nan, np.inf])
arr = np.ma.masked_invalid(Series())
assert_array_equal(arr._data, np.array(Series()))
assert_array_equal(arr._mask, [False, True, True])
@pytest.mark.parametrize("copy", [True, False])
def test_masked_invalid_full_mask(self, copy):
# Matplotlib relied on masked_invalid always returning a full mask
# (Also astropy projects, but were ok with it gh-22720 and gh-22842)
a = np.ma.array([1, 2, 3, 4])
assert a._mask is nomask
res = np.ma.masked_invalid(a, copy=copy)
assert res.mask is not nomask
# mask of a should not be mutated
assert a.mask is nomask
assert np.may_share_memory(a._data, res._data) != copy
def test_choose(self):
# Test choose
choices = [[0, 1, 2, 3], [10, 11, 12, 13],
[20, 21, 22, 23], [30, 31, 32, 33]]
chosen = choose([2, 3, 1, 0], choices)
assert_equal(chosen, array([20, 31, 12, 3]))
chosen = choose([2, 4, 1, 0], choices, mode='clip')
assert_equal(chosen, array([20, 31, 12, 3]))
chosen = choose([2, 4, 1, 0], choices, mode='wrap')
assert_equal(chosen, array([20, 1, 12, 3]))
# Check with some masked indices
indices_ = array([2, 4, 1, 0], mask=[1, 0, 0, 1])
chosen = choose(indices_, choices, mode='wrap')
assert_equal(chosen, array([99, 1, 12, 99]))
assert_equal(chosen.mask, [1, 0, 0, 1])
# Check with some masked choices
choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
[1, 0, 0, 0], [0, 0, 0, 0]])
indices_ = [2, 3, 1, 0]
chosen = choose(indices_, choices, mode='wrap')
assert_equal(chosen, array([20, 31, 12, 3]))
assert_equal(chosen.mask, [1, 0, 0, 1])
def test_choose_with_out(self):
# Test choose with an explicit out keyword
choices = [[0, 1, 2, 3], [10, 11, 12, 13],
[20, 21, 22, 23], [30, 31, 32, 33]]
store = empty(4, dtype=int)
chosen = choose([2, 3, 1, 0], choices, out=store)
assert_equal(store, array([20, 31, 12, 3]))
assert_(store is chosen)
# Check with some masked indices + out
store = empty(4, dtype=int)
indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
chosen = choose(indices_, choices, mode='wrap', out=store)
assert_equal(store, array([99, 31, 12, 99]))
assert_equal(store.mask, [1, 0, 0, 1])
# Check with some masked choices + out ina ndarray !
choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
[1, 0, 0, 0], [0, 0, 0, 0]])
indices_ = [2, 3, 1, 0]
store = empty(4, dtype=int).view(ndarray)
chosen = choose(indices_, choices, mode='wrap', out=store)
assert_equal(store, array([999999, 31, 12, 999999]))
def test_reshape(self):
a = arange(10)
a[0] = masked
# Try the default
b = a.reshape((5, 2))
assert_equal(b.shape, (5, 2))
assert_(b.flags['C'])
# Try w/ arguments as list instead of tuple
b = a.reshape(5, 2)
assert_equal(b.shape, (5, 2))
assert_(b.flags['C'])
# Try w/ order
b = a.reshape((5, 2), order='F')
assert_equal(b.shape, (5, 2))
assert_(b.flags['F'])
# Try w/ order
b = a.reshape(5, 2, order='F')
assert_equal(b.shape, (5, 2))
assert_(b.flags['F'])
c = np.reshape(a, (2, 5))
assert_(isinstance(c, MaskedArray))
assert_equal(c.shape, (2, 5))
assert_(c[0, 0] is masked)
assert_(c.flags['C'])
def test_make_mask_descr(self):
# Flexible
ntype = [('a', float), ('b', float)]
test = make_mask_descr(ntype)
assert_equal(test, [('a', bool), ('b', bool)])
assert_(test is make_mask_descr(test))
# Standard w/ shape
ntype = (float, 2)
test = make_mask_descr(ntype)
assert_equal(test, (bool, 2))
assert_(test is make_mask_descr(test))
# Standard standard
ntype = float
test = make_mask_descr(ntype)
assert_equal(test, np.dtype(bool))
assert_(test is make_mask_descr(test))
# Nested
ntype = [('a', float), ('b', [('ba', float), ('bb', float)])]
test = make_mask_descr(ntype)
control = np.dtype([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])])
assert_equal(test, control)
assert_(test is make_mask_descr(test))
# Named+ shape
ntype = [('a', (float, 2))]
test = make_mask_descr(ntype)
assert_equal(test, np.dtype([('a', (bool, 2))]))
assert_(test is make_mask_descr(test))
# 2 names
ntype = [(('A', 'a'), float)]
test = make_mask_descr(ntype)
assert_equal(test, np.dtype([(('A', 'a'), bool)]))
assert_(test is make_mask_descr(test))
# nested boolean types should preserve identity
base_type = np.dtype([('a', int, 3)])
base_mtype = make_mask_descr(base_type)
sub_type = np.dtype([('a', int), ('b', base_mtype)])
test = make_mask_descr(sub_type)
assert_equal(test, np.dtype([('a', bool), ('b', [('a', bool, 3)])]))
assert_(test.fields['b'][0] is base_mtype)
def test_make_mask(self):
# Test make_mask
# w/ a list as an input
mask = [0, 1]
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [0, 1])
# w/ a ndarray as an input
mask = np.array([0, 1], dtype=bool)
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [0, 1])
# w/ a flexible-type ndarray as an input - use default
mdtype = [('a', bool), ('b', bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [1, 1])
# w/ a flexible-type ndarray as an input - use input dtype
mdtype = [('a', bool), ('b', bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask, dtype=mask.dtype)
assert_equal(test.dtype, mdtype)
assert_equal(test, mask)
# w/ a flexible-type ndarray as an input - use input dtype
mdtype = [('a', float), ('b', float)]
bdtype = [('a', bool), ('b', bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask, dtype=mask.dtype)
assert_equal(test.dtype, bdtype)
assert_equal(test, np.array([(0, 0), (0, 1)], dtype=bdtype))
# Ensure this also works for void
mask = np.array((False, True), dtype='?,?')[()]
assert_(isinstance(mask, np.void))
test = make_mask(mask, dtype=mask.dtype)
assert_equal(test, mask)
assert_(test is not mask)
mask = np.array((0, 1), dtype='i4,i4')[()]
test2 = make_mask(mask, dtype=mask.dtype)
assert_equal(test2, test)
# test that nomask is returned when m is nomask.
bools = [True, False]
dtypes = [MaskType, float]
msgformat = 'copy=%s, shrink=%s, dtype=%s'
for cpy, shr, dt in itertools.product(bools, bools, dtypes):
res = make_mask(nomask, copy=cpy, shrink=shr, dtype=dt)
assert_(res is nomask, msgformat % (cpy, shr, dt))
def test_mask_or(self):
# Initialize
mtype = [('a', bool), ('b', bool)]
mask = np.array([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype)
# Test using nomask as input
test = mask_or(mask, nomask)
assert_equal(test, mask)
test = mask_or(nomask, mask)
assert_equal(test, mask)
# Using False as input
test = mask_or(mask, False)
assert_equal(test, mask)
# Using another array w / the same dtype
other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype)
test = mask_or(mask, other)
control = np.array([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype)
assert_equal(test, control)
# Using another array w / a different dtype
othertype = [('A', bool), ('B', bool)]
other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype)
try:
test = mask_or(mask, other)
except ValueError:
pass
# Using nested arrays
dtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
amask = np.array([(0, (1, 0)), (0, (1, 0))], dtype=dtype)
bmask = np.array([(1, (0, 1)), (0, (0, 0))], dtype=dtype)
cntrl = np.array([(1, (1, 1)), (0, (1, 0))], dtype=dtype)
assert_equal(mask_or(amask, bmask), cntrl)
a = np.array([False, False])
assert mask_or(a, a) is nomask # gh-27360
def test_allequal(self):
x = array([1, 2, 3], mask=[0, 0, 0])
y = array([1, 2, 3], mask=[1, 0, 0])
z = array([[1, 2, 3], [4, 5, 6]], mask=[[0, 0, 0], [1, 1, 1]])
assert allequal(x, y)
assert not allequal(x, y, fill_value=False)
assert allequal(x, z)
# test allequal for the same input, with mask=nomask, this test is for
# the scenario raised in https://github.com/numpy/numpy/issues/27201
assert allequal(x, x)
assert allequal(x, x, fill_value=False)
assert allequal(y, y)
assert not allequal(y, y, fill_value=False)
def test_flatten_mask(self):
# Tests flatten mask
# Standard dtype
mask = np.array([0, 0, 1], dtype=bool)
assert_equal(flatten_mask(mask), mask)
# Flexible dtype
mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
test = flatten_mask(mask)
control = np.array([0, 0, 0, 1], dtype=bool)
assert_equal(test, control)
mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
data = [(0, (0, 0)), (0, (0, 1))]
mask = np.array(data, dtype=mdtype)
test = flatten_mask(mask)
control = np.array([0, 0, 0, 0, 0, 1], dtype=bool)
assert_equal(test, control)
def test_on_ndarray(self):
# Test functions on ndarrays
a = np.array([1, 2, 3, 4])
m = array(a, mask=False)
test = anom(a)
assert_equal(test, m.anom())
test = reshape(a, (2, 2))
assert_equal(test, m.reshape(2, 2))
def test_compress(self):
# Test compress function on ndarray and masked array
# Address Github #2495.
arr = np.arange(8)
arr.shape = 4, 2
cond = np.array([True, False, True, True])
control = arr[[0, 2, 3]]
test = np.ma.compress(cond, arr, axis=0)
assert_equal(test, control)
marr = np.ma.array(arr)
test = np.ma.compress(cond, marr, axis=0)
assert_equal(test, control)
def test_compressed(self):
# Test ma.compressed function.
# Address gh-4026
a = np.ma.array([1, 2])
test = np.ma.compressed(a)
assert_(type(test) is np.ndarray)
# Test case when input data is ndarray subclass
class A(np.ndarray):
pass
a = np.ma.array(A(shape=0))
test = np.ma.compressed(a)
assert_(type(test) is A)
# Test that compress flattens
test = np.ma.compressed([[1], [2]])
assert_equal(test.ndim, 1)
test = np.ma.compressed([[[[[1]]]]])
assert_equal(test.ndim, 1)
# Test case when input is MaskedArray subclass
class M(MaskedArray):
pass
test = np.ma.compressed(M([[[]], [[]]]))
assert_equal(test.ndim, 1)
# with .compressed() overridden
class M(MaskedArray):
def compressed(self):
return 42
test = np.ma.compressed(M([[[]], [[]]]))
assert_equal(test, 42)
def test_convolve(self):
a = masked_equal(np.arange(5), 2)
b = np.array([1, 1])
result = masked_equal([0, 1, -1, -1, 7, 4], -1)
test = np.ma.convolve(a, b, mode='full')
assert_equal(test, result)
test = np.ma.convolve(a, b, mode='same')
assert_equal(test, result[:-1])
test = np.ma.convolve(a, b, mode='valid')
assert_equal(test, result[1:-1])
result = masked_equal([0, 1, 1, 3, 7, 4], -1)
test = np.ma.convolve(a, b, mode='full', propagate_mask=False)
assert_equal(test, result)
test = np.ma.convolve(a, b, mode='same', propagate_mask=False)
assert_equal(test, result[:-1])
test = np.ma.convolve(a, b, mode='valid', propagate_mask=False)
assert_equal(test, result[1:-1])
test = np.ma.convolve([1, 1], [1, 1, 1])
assert_equal(test, masked_equal([1, 2, 2, 1], -1))
a = [1, 1]
b = masked_equal([1, -1, -1, 1], -1)
test = np.ma.convolve(a, b, propagate_mask=False)
assert_equal(test, masked_equal([1, 1, -1, 1, 1], -1))
test = np.ma.convolve(a, b, propagate_mask=True)
assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1))
| TestMaskedArrayFunctions |
python | google__pytype | third_party/cpython/umarshal.py | {
"start": 1302,
"end": 2289
} | class ____:
def __init__(self, **kwds: Any):
self.__dict__.update(kwds)
def __repr__(self) -> str:
return f"Code(**{self.__dict__})"
co_localsplusnames: Tuple[str]
co_localspluskinds: Tuple[int]
def get_localsplus_names(self, select_kind: int) -> Tuple[str, ...]:
varnames: list[str] = []
for name, kind in zip(self.co_localsplusnames,
self.co_localspluskinds):
if kind & select_kind:
varnames.append(name)
return tuple(varnames)
@property
def co_varnames(self) -> Tuple[str, ...]:
return self.get_localsplus_names(CO_FAST_LOCAL)
@property
def co_cellvars(self) -> Tuple[str, ...]:
return self.get_localsplus_names(CO_FAST_CELL)
@property
def co_freevars(self) -> Tuple[str, ...]:
return self.get_localsplus_names(CO_FAST_FREE)
@property
def co_nlocals(self) -> int:
return len(self.co_varnames)
| Code |
python | pydantic__pydantic | tests/benchmarks/basemodel_eq_performance.py | {
"start": 2759,
"end": 3918
} | class ____(pydantic.BaseModel, frozen=True):
def __eq__(self, other: Any) -> bool:
if isinstance(other, pydantic.BaseModel):
# When comparing instances of generic types for equality, as long as all field values are equal,
# only require their generic origin types to be equal, rather than exact type equality.
# This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__
other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__
model_fields = type(self).model_fields.keys()
getter = operator.itemgetter(*model_fields) if model_fields else lambda _: None
return (
self_type == other_type
and getter(self.__dict__) == getter(other.__dict__)
and self.__pydantic_private__ == other.__pydantic_private__
and self.__pydantic_extra__ == other.__pydantic_extra__
)
else:
return NotImplemented # delegate to the other item in the comparison
| ItemGetterEqModel |
python | encode__httpx | httpx/_models.py | {
"start": 12179,
"end": 17449
} | class ____:
def __init__(
self,
method: str,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
stream: SyncByteStream | AsyncByteStream | None = None,
extensions: RequestExtensions | None = None,
) -> None:
self.method = method.upper()
self.url = URL(url) if params is None else URL(url, params=params)
self.headers = Headers(headers)
self.extensions = {} if extensions is None else dict(extensions)
if cookies:
Cookies(cookies).set_cookie_header(self)
if stream is None:
content_type: str | None = self.headers.get("content-type")
headers, stream = encode_request(
content=content,
data=data,
files=files,
json=json,
boundary=get_multipart_boundary_from_content_type(
content_type=content_type.encode(self.headers.encoding)
if content_type
else None
),
)
self._prepare(headers)
self.stream = stream
# Load the request body, except for streaming content.
if isinstance(stream, ByteStream):
self.read()
else:
# There's an important distinction between `Request(content=...)`,
# and `Request(stream=...)`.
#
# Using `content=...` implies automatically populated `Host` and content
# headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
#
# Using `stream=...` will not automatically include *any*
# auto-populated headers.
#
# As an end-user you don't really need `stream=...`. It's only
# useful when:
#
# * Preserving the request stream when copying requests, eg for redirects.
# * Creating request instances on the *server-side* of the transport API.
self.stream = stream
def _prepare(self, default_headers: dict[str, str]) -> None:
for key, value in default_headers.items():
# Ignore Transfer-Encoding if the Content-Length has been set explicitly.
if key.lower() == "transfer-encoding" and "Content-Length" in self.headers:
continue
self.headers.setdefault(key, value)
auto_headers: list[tuple[bytes, bytes]] = []
has_host = "Host" in self.headers
has_content_length = (
"Content-Length" in self.headers or "Transfer-Encoding" in self.headers
)
if not has_host and self.url.host:
auto_headers.append((b"Host", self.url.netloc))
if not has_content_length and self.method in ("POST", "PUT", "PATCH"):
auto_headers.append((b"Content-Length", b"0"))
self.headers = Headers(auto_headers + self.headers.raw)
@property
def content(self) -> bytes:
if not hasattr(self, "_content"):
raise RequestNotRead()
return self._content
def read(self) -> bytes:
"""
Read and return the request content.
"""
if not hasattr(self, "_content"):
assert isinstance(self.stream, typing.Iterable)
self._content = b"".join(self.stream)
if not isinstance(self.stream, ByteStream):
# If a streaming request has been read entirely into memory, then
# we can replace the stream with a raw bytes implementation,
# to ensure that any non-replayable streams can still be used.
self.stream = ByteStream(self._content)
return self._content
async def aread(self) -> bytes:
"""
Read and return the request content.
"""
if not hasattr(self, "_content"):
assert isinstance(self.stream, typing.AsyncIterable)
self._content = b"".join([part async for part in self.stream])
if not isinstance(self.stream, ByteStream):
# If a streaming request has been read entirely into memory, then
# we can replace the stream with a raw bytes implementation,
# to ensure that any non-replayable streams can still be used.
self.stream = ByteStream(self._content)
return self._content
def __repr__(self) -> str:
class_name = self.__class__.__name__
url = str(self.url)
return f"<{class_name}({self.method!r}, {url!r})>"
def __getstate__(self) -> dict[str, typing.Any]:
return {
name: value
for name, value in self.__dict__.items()
if name not in ["extensions", "stream"]
}
def __setstate__(self, state: dict[str, typing.Any]) -> None:
for name, value in state.items():
setattr(self, name, value)
self.extensions = {}
self.stream = UnattachedStream()
| Request |
python | django__django | tests/multiple_database/tests.py | {
"start": 75395,
"end": 77644
} | class ____(TestCase):
databases = {"default", "other"}
def test_auth_manager(self):
"The methods on the auth manager obey database hints"
# Create one user using default allocation policy
User.objects.create_user("alice", "alice@example.com")
# Create another user, explicitly specifying the database
User.objects.db_manager("default").create_user("bob", "bob@example.com")
# The second user only exists on the other database
alice = User.objects.using("other").get(username="alice")
self.assertEqual(alice.username, "alice")
self.assertEqual(alice._state.db, "other")
with self.assertRaises(User.DoesNotExist):
User.objects.using("default").get(username="alice")
# The second user only exists on the default database
bob = User.objects.using("default").get(username="bob")
self.assertEqual(bob.username, "bob")
self.assertEqual(bob._state.db, "default")
with self.assertRaises(User.DoesNotExist):
User.objects.using("other").get(username="bob")
# That is... there is one user on each database
self.assertEqual(User.objects.using("default").count(), 1)
self.assertEqual(User.objects.using("other").count(), 1)
def test_dumpdata(self):
"dumpdata honors allow_migrate restrictions on the router"
User.objects.create_user("alice", "alice@example.com")
User.objects.db_manager("default").create_user("bob", "bob@example.com")
# dumping the default database doesn't try to include auth because
# allow_migrate prohibits auth on default
new_io = StringIO()
management.call_command(
"dumpdata", "auth", format="json", database="default", stdout=new_io
)
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, "[]")
# dumping the other database does include auth
new_io = StringIO()
management.call_command(
"dumpdata", "auth", format="json", database="other", stdout=new_io
)
command_output = new_io.getvalue().strip()
self.assertIn('"email": "alice@example.com"', command_output)
| AuthTestCase |
python | sympy__sympy | sympy/solvers/diophantine/diophantine.py | {
"start": 30323,
"end": 30877
} | class ____(DiophantineEquationType):
"""
Representation of a homogeneous general quadratic.
No solver is currently implemented for this equation type.
"""
name = 'homogeneous_general_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
# there may be Pow keys like x**2 or Mul keys like x*y
return any(k.is_Mul for k in self.coeff) and self.homogeneous
| HomogeneousGeneralQuadratic |
python | PrefectHQ__prefect | tests/test_serializers.py | {
"start": 13171,
"end": 15401
} | class ____:
@pytest.mark.parametrize("data", SERIALIZER_TEST_CASES)
def test_simple_roundtrip(self, data: Any):
serializer = CompressedSerializer(serializer="pickle")
serialized = serializer.dumps(data)
assert serializer.loads(serialized) == data
@pytest.mark.parametrize("lib", ["bz2", "lzma", "zlib"])
def test_allows_stdlib_compression_libraries(self, lib):
serializer = CompressedSerializer(compressionlib=lib, serializer="pickle")
serialized = serializer.dumps("test")
assert serializer.loads(serialized) == "test"
def test_uses_alternative_compression_library(
self, monkeypatch: pytest.MonkeyPatch
):
compress_mock = MagicMock(return_value=b"test")
decompress_mock = MagicMock(return_value=PickleSerializer().dumps("test"))
monkeypatch.setattr("zlib.compress", compress_mock)
monkeypatch.setattr("zlib.decompress", decompress_mock)
serializer = CompressedSerializer(compressionlib="zlib", serializer="pickle")
serializer.dumps("test")
serializer.loads(b"test")
compress_mock.assert_called_once()
decompress_mock.assert_called_once()
def test_uses_given_serializer(self, monkeypatch: pytest.MonkeyPatch):
compress_mock = MagicMock(return_value=b"test")
decompress_mock = MagicMock(return_value=JSONSerializer().dumps("test"))
monkeypatch.setattr("zlib.compress", compress_mock)
monkeypatch.setattr("zlib.decompress", decompress_mock)
serializer = CompressedSerializer(compressionlib="zlib", serializer="json")
serializer.dumps("test")
serializer.loads(b"test")
compress_mock.assert_called_once()
decompress_mock.assert_called_once()
def test_pickle_shorthand(self):
serializer = Serializer(type="compressed/pickle")
assert isinstance(serializer, CompressedSerializer)
assert isinstance(serializer.serializer, PickleSerializer)
def test_json_shorthand(self):
serializer = Serializer(type="compressed/json")
assert isinstance(serializer, CompressedSerializer)
assert isinstance(serializer.serializer, JSONSerializer)
| TestCompressedSerializer |
python | google__pytype | pytype/file_utils_test.py | {
"start": 6594,
"end": 7751
} | class ____(unittest.TestCase):
def test_ignore_file(self):
with test_utils.Tempdir() as d:
d.create_file(".ignore.py")
self.assertEqual(file_utils.expand_source_files(".", cwd=d.path), set())
def test_find_file(self):
with test_utils.Tempdir() as d:
d.create_file(".find.py")
self.assertEqual(
file_utils.expand_source_files(".*", cwd=d.path),
{file_utils.expand_path(path_utils.join(d.path, ".find.py"))},
)
def test_ignore_dir(self):
with test_utils.Tempdir() as d:
d.create_file(file_utils.replace_separator("d1/.d2/ignore.py"))
self.assertEqual(
file_utils.expand_source_files(
file_utils.replace_separator("d1/**/*"), cwd=d.path
),
set(),
)
def test_find_dir(self):
with test_utils.Tempdir() as d:
d.create_file(file_utils.replace_separator(".d/find.py"))
self.assertEqual(
file_utils.expand_source_files(
file_utils.replace_separator(".d/**/*"), cwd=d.path
),
{file_utils.expand_path(path_utils.join(d.path, ".d", "find.py"))},
)
| TestExpandHiddenFiles |
python | gevent__gevent | src/gevent/tests/test__pool.py | {
"start": 16987,
"end": 17508
} | class ____(greentest.TestCase):
error_fatal = False
def test(self):
p = gevent.pool.Pool(3)
self.assertRaises(ExpectedException, p.map, lambda x: None, error_iter())
gevent.sleep(0.001)
def test_unordered(self):
p = gevent.pool.Pool(3)
def unordered():
return list(p.imap_unordered(lambda x: None, error_iter()))
self.assertRaises(ExpectedException, unordered)
gevent.sleep(0.001)
def divide_by(x):
return 1.0 / x
| TestErrorInIterator |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 5616,
"end": 13155
} | class ____:
__slots__ = ("client",)
def __init__(self, client: Client):
self.client = client
def start(self, id: uuid.UUID, pid: int, when: datetime) -> TIRunContext:
"""Tell the API server that this TI has started running."""
body = TIEnterRunningPayload(pid=pid, hostname=get_hostname(), unixname=getuser(), start_date=when)
resp = self.client.patch(f"task-instances/{id}/run", content=body.model_dump_json())
return TIRunContext.model_validate_json(resp.read())
def finish(self, id: uuid.UUID, state: TerminalStateNonSuccess, when: datetime, rendered_map_index):
"""Tell the API server that this TI has reached a terminal state."""
if state == TaskInstanceState.SUCCESS:
raise ValueError("Logic error. SUCCESS state should call the `succeed` function instead")
# TODO: handle the naming better. finish sounds wrong as "even" deferred is essentially finishing.
body = TITerminalStatePayload(
end_date=when, state=TerminalStateNonSuccess(state), rendered_map_index=rendered_map_index
)
self.client.patch(f"task-instances/{id}/state", content=body.model_dump_json())
def retry(self, id: uuid.UUID, end_date: datetime, rendered_map_index):
"""Tell the API server that this TI has failed and reached a up_for_retry state."""
body = TIRetryStatePayload(end_date=end_date, rendered_map_index=rendered_map_index)
self.client.patch(f"task-instances/{id}/state", content=body.model_dump_json())
def succeed(self, id: uuid.UUID, when: datetime, task_outlets, outlet_events, rendered_map_index):
"""Tell the API server that this TI has succeeded."""
body = TISuccessStatePayload(
end_date=when,
task_outlets=task_outlets,
outlet_events=outlet_events,
rendered_map_index=rendered_map_index,
)
self.client.patch(f"task-instances/{id}/state", content=body.model_dump_json())
def defer(self, id: uuid.UUID, msg):
"""Tell the API server that this TI has been deferred."""
body = TIDeferredStatePayload(**msg.model_dump(exclude_unset=True, exclude={"type"}))
# Create a deferred state payload from msg
self.client.patch(f"task-instances/{id}/state", content=body.model_dump_json())
def reschedule(self, id: uuid.UUID, msg: RescheduleTask):
"""Tell the API server that this TI has been reschduled."""
body = TIRescheduleStatePayload(**msg.model_dump(exclude_unset=True, exclude={"type"}))
# Create a reschedule state payload from msg
self.client.patch(f"task-instances/{id}/state", content=body.model_dump_json())
def heartbeat(self, id: uuid.UUID, pid: int):
body = TIHeartbeatInfo(pid=pid, hostname=get_hostname())
self.client.put(f"task-instances/{id}/heartbeat", content=body.model_dump_json())
def skip_downstream_tasks(self, id: uuid.UUID, msg: SkipDownstreamTasks):
"""Tell the API server to skip the downstream tasks of this TI."""
body = TISkippedDownstreamTasksStatePayload(tasks=msg.tasks)
self.client.patch(f"task-instances/{id}/skip-downstream", content=body.model_dump_json())
def set_rtif(self, id: uuid.UUID, body: dict[str, str]) -> OKResponse:
"""Set Rendered Task Instance Fields via the API server."""
self.client.put(f"task-instances/{id}/rtif", json=body)
# Any error from the server will anyway be propagated down to the supervisor,
# so we choose to send a generic response to the supervisor over the server response to
# decouple from the server response string
return OKResponse(ok=True)
def set_rendered_map_index(self, id: uuid.UUID, rendered_map_index: str) -> OKResponse:
"""Set rendered_map_index for a task instance via the API server."""
self.client.patch(f"task-instances/{id}/rendered-map-index", json=rendered_map_index)
return OKResponse(ok=True)
def get_previous_successful_dagrun(self, id: uuid.UUID) -> PrevSuccessfulDagRunResponse:
"""
Get the previous successful dag run for a given task instance.
The data from it is used to get values for Task Context.
"""
resp = self.client.get(f"task-instances/{id}/previous-successful-dagrun")
return PrevSuccessfulDagRunResponse.model_validate_json(resp.read())
def get_reschedule_start_date(self, id: uuid.UUID, try_number: int = 1) -> TaskRescheduleStartDate:
"""Get the start date of a task reschedule via the API server."""
resp = self.client.get(f"task-reschedules/{id}/start_date", params={"try_number": try_number})
return TaskRescheduleStartDate.model_construct(start_date=resp.json())
def get_count(
self,
dag_id: str,
map_index: int | None = None,
task_ids: list[str] | None = None,
task_group_id: str | None = None,
logical_dates: list[datetime] | None = None,
run_ids: list[str] | None = None,
states: list[str] | None = None,
) -> TICount:
"""Get count of task instances matching the given criteria."""
params: dict[str, Any]
params = {
"dag_id": dag_id,
"task_ids": task_ids,
"task_group_id": task_group_id,
"logical_dates": [d.isoformat() for d in logical_dates] if logical_dates is not None else None,
"run_ids": run_ids,
"states": states,
}
# Remove None values from params
params = {k: v for k, v in params.items() if v is not None}
if map_index is not None and map_index >= 0:
params.update({"map_index": map_index})
resp = self.client.get("task-instances/count", params=params)
return TICount(count=resp.json())
def get_task_states(
self,
dag_id: str,
map_index: int | None = None,
task_ids: list[str] | None = None,
task_group_id: str | None = None,
logical_dates: list[datetime] | None = None,
run_ids: list[str] | None = None,
) -> TaskStatesResponse:
"""Get task states given criteria."""
params: dict[str, Any]
params = {
"dag_id": dag_id,
"task_ids": task_ids,
"task_group_id": task_group_id,
"logical_dates": [d.isoformat() for d in logical_dates] if logical_dates is not None else None,
"run_ids": run_ids,
}
# Remove None values from params
params = {k: v for k, v in params.items() if v is not None}
if map_index is not None and map_index >= 0:
params.update({"map_index": map_index})
resp = self.client.get("task-instances/states", params=params)
return TaskStatesResponse.model_validate_json(resp.read())
def get_task_breakcrumbs(self, dag_id: str, run_id: str) -> TaskBreadcrumbsResponse:
params = {"dag_id": dag_id, "run_id": run_id}
resp = self.client.get("task-instances/breadcrumbs", params=params)
return TaskBreadcrumbsResponse.model_validate_json(resp.read())
def validate_inlets_and_outlets(self, id: uuid.UUID) -> InactiveAssetsResponse:
"""Validate whether there're inactive assets in inlets and outlets of a given task instance."""
resp = self.client.get(f"task-instances/{id}/validate-inlets-and-outlets")
return InactiveAssetsResponse.model_validate_json(resp.read())
| TaskInstanceOperations |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 22053,
"end": 22222
} | class ____(QtWidgets.QMainWindow):
closing = QtCore.Signal()
def closeEvent(self, event):
self.closing.emit()
super().closeEvent(event)
| MainWindow |
python | doocs__leetcode | solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/Solution.py | {
"start": 0,
"end": 183
} | class ____:
def checkStrings(self, s1: str, s2: str) -> bool:
return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted(
s2[1::2]
)
| Solution |
python | tensorflow__tensorflow | tensorflow/compiler/tests/reverse_ops_test.py | {
"start": 1014,
"end": 2539
} | class ____(xla_test.XLATestCase):
def testReverseOneDim(self):
shape = (7, 5, 9, 11)
for revdim in range(-len(shape), len(shape)):
self._AssertReverseEqual([revdim], shape)
def testReverseMoreThanOneDim(self):
shape = (7, 5, 9, 11)
# The offset is used to test various (but not all) combinations of negative
# and positive axis indices that are guaranteed to not collide at the same
# index.
for revdims in itertools.chain.from_iterable(
itertools.combinations(range(-offset,
len(shape) - offset), k)
for k in range(2,
len(shape) + 1)
for offset in range(0, len(shape))):
self._AssertReverseEqual(revdims, shape)
def _AssertReverseEqual(self, revdims, shape):
np.random.seed(120)
pval = np.random.randint(0, 100, size=shape).astype(float)
with self.session():
with self.test_scope():
p = array_ops.placeholder(dtypes.int32, shape=shape)
axis = constant_op.constant(
np.array(revdims, dtype=np.int32),
shape=(len(revdims),),
dtype=dtypes.int32)
rval = array_ops.reverse(p, axis).eval({p: pval})
slices = tuple(
slice(-1, None, -1)
if d in revdims or d - len(shape) in revdims else slice(None)
for d in range(len(shape))
)
self.assertEqual(pval[slices].flatten().tolist(), rval.flatten().tolist())
if __name__ == '__main__':
googletest.main()
| ReverseOpsTest |
python | getsentry__sentry | src/sentry/seer/autofix/utils.py | {
"start": 3179,
"end": 3350
} | class ____(BaseModel):
status: CodingAgentStatus | None = None
agent_url: str | None = None
results: list[CodingAgentResult] | None = None
| CodingAgentStateUpdate |
python | aio-libs__aiohttp | examples/basic_auth_middleware.py | {
"start": 681,
"end": 1644
} | class ____:
"""Middleware that adds Basic Authentication to all requests."""
def __init__(self, username: str, password: str) -> None:
self.username = username
self.password = password
self._auth_header = self._encode_credentials()
def _encode_credentials(self) -> str:
"""Encode username and password to base64."""
credentials = f"{self.username}:{self.password}"
encoded = base64.b64encode(credentials.encode()).decode()
return f"Basic {encoded}"
async def __call__(
self,
request: ClientRequest,
handler: ClientHandlerType,
) -> ClientResponse:
"""Add Basic Auth header to the request."""
# Only add auth if not already present
if hdrs.AUTHORIZATION not in request.headers:
request.headers[hdrs.AUTHORIZATION] = self._auth_header
# Proceed with the request
return await handler(request)
| BasicAuthMiddleware |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py | {
"start": 8270,
"end": 8607
} | class ____(BaseModel):
"""Schema for TaskInstance model with minimal required fields needed for Runtime."""
id: uuid.UUID
task_id: str
dag_id: str
run_id: str
try_number: int
dag_version_id: uuid.UUID
map_index: int = -1
hostname: str | None = None
context_carrier: dict | None = None
| TaskInstance |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/redshift.py | {
"start": 705,
"end": 1323
} | class ____(BaseSettings):
# BaseSettings will retrieve this environment variable
REDSHIFT_DATABASE: str
REDSHIFT_HOST: str
REDSHIFT_PASSWORD: str
REDSHIFT_PORT: int
REDSHIFT_USERNAME: str
REDSHIFT_SSLMODE: str
@property
def connection_string(self) -> RedshiftDsn:
return RedshiftDsn(
f"redshift+psycopg2://{self.REDSHIFT_USERNAME}:{self.REDSHIFT_PASSWORD}@"
f"{self.REDSHIFT_HOST}:{self.REDSHIFT_PORT}/{self.REDSHIFT_DATABASE}?"
f"sslmode={self.REDSHIFT_SSLMODE}",
scheme="redshift+psycopg2",
)
| RedshiftConnectionConfig |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/plugins.py | {
"start": 4094,
"end": 4237
} | class ____(BaseModel):
"""Plugin Collection serializer."""
plugins: list[PluginResponse]
total_entries: int
| PluginCollectionResponse |
python | scipy__scipy | scipy/special/tests/test_legendre.py | {
"start": 2307,
"end": 12690
} | class ____:
@pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
@pytest.mark.parametrize("m_max", [5, 4])
@pytest.mark.parametrize("n_max", [7, 10])
def test_lpmn(self, shape, n_max, m_max):
rng = np.random.default_rng(1234)
x = rng.uniform(-0.99, 0.99, shape)
p_all, p_all_jac, p_all_hess = \
assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
n = np.arange(n_max + 1)
n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
x = np.expand_dims(x, axis = (0, 1))
p, p_jac, p_hess = assoc_legendre_p(n, m, x, diff_n=2)
np.testing.assert_allclose(p, p_all)
np.testing.assert_allclose(p_jac, p_all_jac)
np.testing.assert_allclose(p_hess, p_all_hess)
@pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
@pytest.mark.parametrize("norm", [True, False])
def test_ode(self, shape, norm):
rng = np.random.default_rng(1234)
n = rng.integers(0, 10, shape)
m = rng.integers(-10, 10, shape)
x = rng.uniform(-1, 1, shape)
p, p_jac, p_hess = assoc_legendre_p(n, m, x, norm=norm, diff_n=2)
assert p.shape == shape
assert p_jac.shape == p.shape
assert p_hess.shape == p_jac.shape
np.testing.assert_allclose((1 - x * x) * p_hess,
2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
rtol=1e-05, atol=1e-08)
@pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
def test_all(self, shape):
rng = np.random.default_rng(1234)
n_max = 20
m_max = 20
x = rng.uniform(-0.99, 0.99, shape)
p, p_jac, p_hess = assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
n = np.arange(n_max + 1)
n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
np.testing.assert_allclose((1 - x * x) * p_hess,
2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
rtol=1e-05, atol=1e-08)
@pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
@pytest.mark.parametrize("norm", [True, False])
def test_specific(self, shape, norm):
rng = np.random.default_rng(1234)
x = rng.uniform(-0.99, 0.99, shape)
p, p_jac = assoc_legendre_p_all(4, 4, x, norm=norm, diff_n=1)
np.testing.assert_allclose(p[0, 0],
assoc_legendre_p_0_0(x, norm=norm))
np.testing.assert_allclose(p[0, 1], 0)
np.testing.assert_allclose(p[0, 2], 0)
np.testing.assert_allclose(p[0, 3], 0)
np.testing.assert_allclose(p[0, 4], 0)
np.testing.assert_allclose(p[0, -3], 0)
np.testing.assert_allclose(p[0, -2], 0)
np.testing.assert_allclose(p[0, -1], 0)
np.testing.assert_allclose(p[1, 0],
assoc_legendre_p_1_0(x, norm=norm))
np.testing.assert_allclose(p[1, 1],
assoc_legendre_p_1_1(x, norm=norm))
np.testing.assert_allclose(p[1, 2], 0)
np.testing.assert_allclose(p[1, 3], 0)
np.testing.assert_allclose(p[1, 4], 0)
np.testing.assert_allclose(p[1, -4], 0)
np.testing.assert_allclose(p[1, -3], 0)
np.testing.assert_allclose(p[1, -2], 0)
np.testing.assert_allclose(p[1, -1],
assoc_legendre_p_1_m1(x, norm=norm))
np.testing.assert_allclose(p[2, 0],
assoc_legendre_p_2_0(x, norm=norm))
np.testing.assert_allclose(p[2, 1],
assoc_legendre_p_2_1(x, norm=norm))
np.testing.assert_allclose(p[2, 2],
assoc_legendre_p_2_2(x, norm=norm))
np.testing.assert_allclose(p[2, 3], 0)
np.testing.assert_allclose(p[2, 4], 0)
np.testing.assert_allclose(p[2, -4], 0)
np.testing.assert_allclose(p[2, -3], 0)
np.testing.assert_allclose(p[2, -2],
assoc_legendre_p_2_m2(x, norm=norm))
np.testing.assert_allclose(p[2, -1],
assoc_legendre_p_2_m1(x, norm=norm))
np.testing.assert_allclose(p[3, 0],
assoc_legendre_p_3_0(x, norm=norm))
np.testing.assert_allclose(p[3, 1],
assoc_legendre_p_3_1(x, norm=norm))
np.testing.assert_allclose(p[3, 2],
assoc_legendre_p_3_2(x, norm=norm))
np.testing.assert_allclose(p[3, 3],
assoc_legendre_p_3_3(x, norm=norm))
np.testing.assert_allclose(p[3, 4], 0)
np.testing.assert_allclose(p[3, -4], 0)
np.testing.assert_allclose(p[3, -3],
assoc_legendre_p_3_m3(x, norm=norm))
np.testing.assert_allclose(p[3, -2],
assoc_legendre_p_3_m2(x, norm=norm))
np.testing.assert_allclose(p[3, -1],
assoc_legendre_p_3_m1(x, norm=norm))
np.testing.assert_allclose(p[4, 0],
assoc_legendre_p_4_0(x, norm=norm))
np.testing.assert_allclose(p[4, 1],
assoc_legendre_p_4_1(x, norm=norm))
np.testing.assert_allclose(p[4, 2],
assoc_legendre_p_4_2(x, norm=norm))
np.testing.assert_allclose(p[4, 3],
assoc_legendre_p_4_3(x, norm=norm))
np.testing.assert_allclose(p[4, 4],
assoc_legendre_p_4_4(x, norm=norm))
np.testing.assert_allclose(p[4, -4],
assoc_legendre_p_4_m4(x, norm=norm))
np.testing.assert_allclose(p[4, -3],
assoc_legendre_p_4_m3(x, norm=norm))
np.testing.assert_allclose(p[4, -2],
assoc_legendre_p_4_m2(x, norm=norm))
np.testing.assert_allclose(p[4, -1],
assoc_legendre_p_4_m1(x, norm=norm))
np.testing.assert_allclose(p_jac[0, 0],
assoc_legendre_p_0_0_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[0, 1], 0)
np.testing.assert_allclose(p_jac[0, 2], 0)
np.testing.assert_allclose(p_jac[0, 3], 0)
np.testing.assert_allclose(p_jac[0, 4], 0)
np.testing.assert_allclose(p_jac[0, -4], 0)
np.testing.assert_allclose(p_jac[0, -3], 0)
np.testing.assert_allclose(p_jac[0, -2], 0)
np.testing.assert_allclose(p_jac[0, -1], 0)
np.testing.assert_allclose(p_jac[1, 0],
assoc_legendre_p_1_0_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[1, 1],
assoc_legendre_p_1_1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[1, 2], 0)
np.testing.assert_allclose(p_jac[1, 3], 0)
np.testing.assert_allclose(p_jac[1, 4], 0)
np.testing.assert_allclose(p_jac[1, -4], 0)
np.testing.assert_allclose(p_jac[1, -3], 0)
np.testing.assert_allclose(p_jac[1, -2], 0)
np.testing.assert_allclose(p_jac[1, -1],
assoc_legendre_p_1_m1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[2, 0],
assoc_legendre_p_2_0_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[2, 1],
assoc_legendre_p_2_1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[2, 2],
assoc_legendre_p_2_2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[2, 3], 0)
np.testing.assert_allclose(p_jac[2, 4], 0)
np.testing.assert_allclose(p_jac[2, -4], 0)
np.testing.assert_allclose(p_jac[2, -3], 0)
np.testing.assert_allclose(p_jac[2, -2],
assoc_legendre_p_2_m2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[2, -1],
assoc_legendre_p_2_m1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, 0],
assoc_legendre_p_3_0_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, 1],
assoc_legendre_p_3_1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, 2],
assoc_legendre_p_3_2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, 3],
assoc_legendre_p_3_3_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, 4], 0)
np.testing.assert_allclose(p_jac[3, -4], 0)
np.testing.assert_allclose(p_jac[3, -3],
assoc_legendre_p_3_m3_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, -2],
assoc_legendre_p_3_m2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[3, -1],
assoc_legendre_p_3_m1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, 0],
assoc_legendre_p_4_0_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, 1],
assoc_legendre_p_4_1_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, 2],
assoc_legendre_p_4_2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, 3],
assoc_legendre_p_4_3_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, 4],
assoc_legendre_p_4_4_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, -4],
assoc_legendre_p_4_m4_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, -3],
assoc_legendre_p_4_m3_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, -2],
assoc_legendre_p_4_m2_jac(x, norm=norm))
np.testing.assert_allclose(p_jac[4, -1],
assoc_legendre_p_4_m1_jac(x, norm=norm))
@pytest.mark.parametrize("m_max", [7])
@pytest.mark.parametrize("n_max", [10])
@pytest.mark.parametrize("x", [1, -1])
def test_all_limits(self, m_max, n_max, x):
p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
n = np.arange(n_max + 1)
np.testing.assert_allclose(p_jac[:, 0],
pow(x, n + 1) * n * (n + 1) / 2)
np.testing.assert_allclose(p_jac[:, 1],
np.where(n >= 1, pow(x, n) * np.inf, 0))
np.testing.assert_allclose(p_jac[:, 2],
np.where(n >= 2, -pow(x, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
np.testing.assert_allclose(p_jac[:, -2],
np.where(n >= 2, -pow(x, n + 1) / 4, 0))
np.testing.assert_allclose(p_jac[:, -1],
np.where(n >= 1, -pow(x, n) * np.inf, 0))
for m in range(3, m_max + 1):
np.testing.assert_allclose(p_jac[:, m], 0)
np.testing.assert_allclose(p_jac[:, -m], 0)
| TestAssocLegendreP |
python | ray-project__ray | python/ray/tests/test_runtime_env_packaging.py | {
"start": 11436,
"end": 13225
} | class ____:
def test_valid_removal(self, random_zip_file_with_top_level_dir):
# This test copies the TOP_LEVEL_DIR_NAME directory, and then it
# shifts the contents of the copied directory into the base tmp_path
# directory. Then it compares the contents of tmp_path with the
# TOP_LEVEL_DIR_NAME directory to ensure that they match.
archive_path = random_zip_file_with_top_level_dir
tmp_path = archive_path[: archive_path.rfind(os.path.sep)]
original_dir_path = os.path.join(tmp_path, TOP_LEVEL_DIR_NAME)
copy_dir_path = os.path.join(tmp_path, TOP_LEVEL_DIR_NAME + "_copy")
copytree(original_dir_path, copy_dir_path)
remove_dir_from_filepaths(tmp_path, TOP_LEVEL_DIR_NAME + "_copy")
dcmp = dircmp(tmp_path, os.path.join(tmp_path, TOP_LEVEL_DIR_NAME))
# Since this test uses the tmp_path as the target directory, and since
# the tmp_path also contains the zip file and the top level directory,
# make sure that the only difference between the tmp_path's contents
# and the top level directory's contents are the zip file from the
# Pytest fixture and the top level directory itself. This implies that
# all files have been extracted from the top level directory and moved
# into the tmp_path.
assert set(dcmp.left_only) == {
ARCHIVE_NAME,
TOP_LEVEL_DIR_NAME,
MAC_OS_ZIP_HIDDEN_DIR_NAME,
}
# Make sure that all the subdirectories and files have been moved to
# the target directory
assert len(dcmp.right_only) == 0
@pytest.mark.parametrize("remove_top_level_directory", [False, True])
@pytest.mark.parametrize("unlink_zip", [False, True])
| TestRemoveDirFromFilepaths |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 30979,
"end": 31802
} | class ____:
"""A contextmanager to capture exceptions and forward them to a
GroupedExceptionHandler."""
def __init__(self, context: str, handler: GroupedExceptionHandler, base: type):
self._context = context
self._handler = handler
self._base = base
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, tb):
if exc_value is not None:
if not issubclass(exc_type, self._base):
return False
self._handler._receive_forwarded(self._context, exc_value, traceback.format_tb(tb))
# Suppress any exception from being re-raised:
# https://docs.python.org/3/reference/datamodel.html#object.__exit__.
return True
ClassPropertyType = TypeVar("ClassPropertyType")
| GroupedExceptionForwarder |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/remote_asset_graph.py | {
"start": 2496,
"end": 5788
} | class ____(BaseAssetNode, ABC):
@abstractmethod
def resolve_to_singular_repo_scoped_node(self) -> "RemoteRepositoryAssetNode": ...
@abstractmethod
def resolve_to_repo_scoped_node(
self, repository_selector: "RepositorySelector"
) -> Optional["RemoteRepositoryAssetNode"]: ...
@property
def execution_set_asset_keys(self) -> AbstractSet[AssetKey]:
return {k for k in self.execution_set_entity_keys if isinstance(k, AssetKey)}
@property
def description(self) -> Optional[str]:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.description
@property
def group_name(self) -> str:
return (
self.resolve_to_singular_repo_scoped_node().asset_node_snap.group_name
or DEFAULT_GROUP_NAME
)
@property
def metadata(self) -> ArbitraryMetadataMapping:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.metadata
@property
def execution_type(self) -> AssetExecutionType:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.execution_type
@property
def pools(self) -> Optional[set[str]]:
return self.resolve_to_singular_repo_scoped_node().pools
@property
def tags(self) -> Mapping[str, str]:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.tags or {}
@property
def owners(self) -> Sequence[str]:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.owners or []
@property
def is_partitioned(self) -> bool:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.partitions is not None
@cached_property
def partitions_def(self) -> Optional[PartitionsDefinition]: # pyright: ignore[reportIncompatibleMethodOverride]
partitions_snap = self.resolve_to_singular_repo_scoped_node().asset_node_snap.partitions
return partitions_snap.get_partitions_definition() if partitions_snap else None
@property
def legacy_freshness_policy(self) -> Optional[LegacyFreshnessPolicy]:
# It is currently not possible to access the freshness policy for an observation definition
# if a materialization definition also exists. This needs to be fixed.
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.legacy_freshness_policy
@property
def freshness_policy(self) -> Optional[FreshnessPolicy]:
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.freshness_policy
@property
def code_version(self) -> Optional[str]:
# It is currently not possible to access the code version for an observation definition if a
# materialization definition also exists. This needs to be fixed.
return self.resolve_to_singular_repo_scoped_node().asset_node_snap.code_version
@property
def job_names(self) -> Sequence[str]:
# It is currently not possible to access the job names for an observation definition if a
# materialization definition also exists. This needs to be fixed.
return (
self.resolve_to_singular_repo_scoped_node().asset_node_snap.job_names
if self.is_executable
else []
)
@whitelist_for_serdes
@record
| RemoteAssetNode |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 15567,
"end": 15668
} | class ____(PydanticValueError):
msg_template = 'value is not a valid IPv6 address'
| IPv6AddressError |
python | python__mypy | mypy/checker.py | {
"start": 8726,
"end": 375034
} | class ____(NodeVisitor[None], TypeCheckerSharedApi):
"""Mypy type checker.
Type check mypy source files that have been semantically analyzed.
You must create a separate instance for each source file.
"""
# Are we type checking a stub?
is_stub = False
# Error message reporter
errors: Errors
# Utility for generating messages
msg: MessageBuilder
# Types of type checked nodes. The first item is the "master" type
# map that will store the final, exported types. Additional items
# are temporary type maps used during type inference, and these
# will be eventually popped and either discarded or merged into
# the master type map.
#
# Avoid accessing this directly, but prefer the lookup_type(),
# has_type() etc. helpers instead.
_type_maps: list[dict[Expression, Type]]
# Helper for managing conditional types
binder: ConditionalTypeBinder
# Helper for type checking expressions
_expr_checker: mypy.checkexpr.ExpressionChecker
pattern_checker: PatternChecker
tscope: Scope
scope: CheckerScope
# Innermost enclosing type
type: TypeInfo | None
# Stack of function return types
return_types: list[Type]
# Flags; true for dynamically typed functions
dynamic_funcs: list[bool]
# Stack of collections of variables with partial types
partial_types: list[PartialTypeScope]
# Vars for which partial type errors are already reported
# (to avoid logically duplicate errors with different error context).
partial_reported: set[Var]
# Short names of Var nodes whose previous inferred type has been widened via assignment.
# NOTE: The names might not be unique, they are only for debugging purposes.
widened_vars: list[str]
globals: SymbolTable
modules: dict[str, MypyFile]
# Nodes that couldn't be checked because some types weren't available. We'll run
# another pass and try these again.
deferred_nodes: list[DeferredNode]
# Type checking pass number (0 = first pass)
pass_num = 0
# Last pass number to take
last_pass = DEFAULT_LAST_PASS
# Have we deferred the current function? If yes, don't infer additional
# types during this pass within the function.
current_node_deferred = False
# Is this file a typeshed stub?
is_typeshed_stub = False
options: Options
# Used for collecting inferred attribute types so that they can be checked
# for consistency.
inferred_attribute_types: dict[Var, Type] | None = None
# Don't infer partial None types if we are processing assignment from Union
no_partial_types: bool = False
# Extra module references not detected during semantic analysis (these are rare cases
# e.g. access to class-level import via instance).
module_refs: set[str]
# A map from variable nodes to a snapshot of the frame ids of the
# frames that were active when the variable was declared. This can
# be used to determine nearest common ancestor frame of a variable's
# declaration and the current frame, which lets us determine if it
# was declared in a different branch of the same `if` statement
# (if that frame is a conditional_frame).
var_decl_frames: dict[Var, set[int]]
# Plugin that provides special type checking rules for specific library
# functions such as open(), etc.
plugin: Plugin
# A helper state to produce unique temporary names on demand.
_unique_id: int
# Fake concrete type used when checking variance
_variance_dummy_type: Instance | None
def __init__(
self,
errors: Errors,
modules: dict[str, MypyFile],
options: Options,
tree: MypyFile,
path: str,
plugin: Plugin,
per_line_checking_time_ns: dict[int, int],
) -> None:
"""Construct a type checker.
Use errors to report type check errors.
"""
self.errors = errors
self.modules = modules
self.options = options
self.tree = tree
self.path = path
self.msg = MessageBuilder(errors, modules)
self.plugin = plugin
self.tscope = Scope()
self.scope = CheckerScope(tree)
self.binder = ConditionalTypeBinder(options)
self.globals = tree.names
self.type = None
self.return_types = []
self.dynamic_funcs = []
self.partial_types = []
self.partial_reported = set()
self.var_decl_frames = {}
self.deferred_nodes = []
self.widened_vars = []
self._type_maps = [{}]
self.module_refs = set()
self.pass_num = 0
self.current_node_deferred = False
self.is_stub = tree.is_stub
self.is_typeshed_stub = tree.is_typeshed_file(options)
self.inferred_attribute_types = None
self.allow_constructor_cache = True
self.local_type_map = LocalTypeMap(self)
# If True, process function definitions. If False, don't. This is used
# for processing module top levels in fine-grained incremental mode.
self.recurse_into_functions = True
# This internal flag is used to track whether we a currently type-checking
# a final declaration (assignment), so that some errors should be suppressed.
# Should not be set manually, use get_final_context/enter_final_context instead.
# NOTE: we use the context manager to avoid "threading" an additional `is_final_def`
# argument through various `checker` and `checkmember` functions.
self._is_final_def = False
# Track when we enter an overload implementation. Some checks should not be applied
# to the implementation signature when specific overloads are available.
# Use `enter_overload_impl` to modify.
self.overload_impl_stack: list[OverloadPart] = []
# This flag is set when we run type-check or attribute access check for the purpose
# of giving a note on possibly missing "await". It is used to avoid infinite recursion.
self.checking_missing_await = False
# While this is True, allow passing an abstract class where Type[T] is expected.
# although this is technically unsafe, this is desirable in some context, for
# example when type-checking class decorators.
self.allow_abstract_call = False
# Child checker objects for specific AST node types
self._expr_checker = mypy.checkexpr.ExpressionChecker(
self, self.msg, self.plugin, per_line_checking_time_ns
)
self.pattern_checker = PatternChecker(self, self.msg, self.plugin, options)
self._unique_id = 0
self._variance_dummy_type = None
@property
def expr_checker(self) -> mypy.checkexpr.ExpressionChecker:
return self._expr_checker
@property
def type_context(self) -> list[Type | None]:
return self._expr_checker.type_context
def reset(self) -> None:
"""Cleanup stale state that might be left over from a typechecking run.
This allows us to reuse TypeChecker objects in fine-grained
incremental mode.
"""
# TODO: verify this is still actually worth it over creating new checkers
self.partial_reported.clear()
self.module_refs.clear()
self.binder = ConditionalTypeBinder(self.options)
self._type_maps[1:] = []
self._type_maps[0].clear()
self.expr_checker.reset()
self.deferred_nodes = []
self.partial_types = []
self.inferred_attribute_types = None
self.scope = CheckerScope(self.tree)
def check_first_pass(self) -> None:
"""Type check the entire file, but defer functions with unresolved references.
Unresolved references are forward references to variables
whose types haven't been inferred yet. They may occur later
in the same file or in a different file that's being processed
later (usually due to an import cycle).
Deferred functions will be processed by check_second_pass().
"""
self.recurse_into_functions = True
with state.strict_optional_set(self.options.strict_optional), checker_state.set(self):
self.errors.set_file(
self.path, self.tree.fullname, scope=self.tscope, options=self.options
)
with self.tscope.module_scope(self.tree.fullname):
with self.enter_partial_types(), self.binder.top_frame_context():
for d in self.tree.defs:
if self.binder.is_unreachable():
if not self.should_report_unreachable_issues():
break
if not self.is_noop_for_reachability(d):
self.msg.unreachable_statement(d)
break
else:
self.accept(d)
assert not self.current_node_deferred
all_ = self.globals.get("__all__")
if all_ is not None and all_.type is not None:
all_node = all_.node
assert all_node is not None
seq_str = self.named_generic_type(
"typing.Sequence", [self.named_type("builtins.str")]
)
if not is_subtype(all_.type, seq_str):
str_seq_s, all_s = format_type_distinctly(
seq_str, all_.type, options=self.options
)
self.fail(
message_registry.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s), all_node
)
def check_second_pass(
self,
todo: Sequence[DeferredNode | FineGrainedDeferredNode] | None = None,
*,
allow_constructor_cache: bool = True,
) -> bool:
"""Run second or following pass of type checking.
This goes through deferred nodes, returning True if there were any.
"""
self.allow_constructor_cache = allow_constructor_cache
self.recurse_into_functions = True
with state.strict_optional_set(self.options.strict_optional), checker_state.set(self):
if not todo and not self.deferred_nodes:
return False
self.errors.set_file(
self.path, self.tree.fullname, scope=self.tscope, options=self.options
)
with self.tscope.module_scope(self.tree.fullname):
self.pass_num += 1
if not todo:
todo = self.deferred_nodes
else:
assert not self.deferred_nodes
self.deferred_nodes = []
done: set[DeferredNodeType | FineGrainedDeferredNodeType] = set()
for node, active_typeinfo in todo:
if node in done:
continue
# This is useful for debugging:
# print("XXX in pass %d, class %s, function %s" %
# (self.pass_num, type_name, node.fullname or node.name))
done.add(node)
with ExitStack() as stack:
if active_typeinfo:
stack.enter_context(self.tscope.class_scope(active_typeinfo))
stack.enter_context(self.scope.push_class(active_typeinfo))
self.check_partial(node)
return True
def check_partial(self, node: DeferredNodeType | FineGrainedDeferredNodeType) -> None:
self.widened_vars = []
if isinstance(node, MypyFile):
self.check_top_level(node)
else:
self.recurse_into_functions = True
with self.binder.top_frame_context():
self.accept(node)
def check_top_level(self, node: MypyFile) -> None:
"""Check only the top-level of a module, skipping function definitions."""
self.recurse_into_functions = False
with self.enter_partial_types():
with self.binder.top_frame_context():
for d in node.defs:
d.accept(self)
assert not self.current_node_deferred
# TODO: Handle __all__
def defer_node(self, node: DeferredNodeType, enclosing_class: TypeInfo | None) -> None:
"""Defer a node for processing during next type-checking pass.
Args:
node: function/method being deferred
enclosing_class: for methods, the class where the method is defined
NOTE: this can't handle nested functions/methods.
"""
# We don't freeze the entire scope since only top-level functions and methods
# can be deferred. Only module/class level scope information is needed.
# Module-level scope information is preserved in the TypeChecker instance.
self.deferred_nodes.append(DeferredNode(node, enclosing_class))
def handle_cannot_determine_type(self, name: str, context: Context) -> None:
node = self.scope.top_level_function()
if self.pass_num < self.last_pass and isinstance(node, FuncDef):
# Don't report an error yet. Just defer. Note that we don't defer
# lambdas because they are coupled to the surrounding function
# through the binder and the inferred type of the lambda, so it
# would get messy.
enclosing_class = self.scope.enclosing_class(node)
self.defer_node(node, enclosing_class)
# Set a marker so that we won't infer additional types in this
# function. Any inferred types could be bogus, because there's at
# least one type that we don't know.
self.current_node_deferred = True
else:
self.msg.cannot_determine_type(name, context)
def accept(self, stmt: Statement) -> None:
"""Type check a node in the given type context."""
try:
stmt.accept(self)
except Exception as err:
report_internal_error(err, self.errors.file, stmt.line, self.errors, self.options)
def accept_loop(
self,
body: Statement,
else_body: Statement | None = None,
*,
exit_condition: Expression | None = None,
on_enter_body: Callable[[], None] | None = None,
) -> None:
"""Repeatedly type check a loop body until the frame doesn't change."""
# The outer frame accumulates the results of all iterations:
with self.binder.frame_context(can_skip=False, conditional_frame=True):
# Check for potential decreases in the number of partial types so as not to stop the
# iteration too early:
partials_old = sum(len(pts.map) for pts in self.partial_types)
# Check if assignment widened the inferred type of a variable; in this case we
# need to iterate again (we only do one extra iteration, since this could go
# on without bound otherwise)
widened_old = len(self.widened_vars)
iter_errors = IterationDependentErrors()
iter = 1
while True:
with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):
if on_enter_body is not None:
on_enter_body()
with IterationErrorWatcher(self.msg.errors, iter_errors):
self.accept(body)
partials_new = sum(len(pts.map) for pts in self.partial_types)
widened_new = len(self.widened_vars)
# Perform multiple iterations if something changed that might affect
# inferred types. Also limit the number of iterations. The limits are
# somewhat arbitrary, but they were chosen to 1) avoid slowdown from
# multiple iterations in common cases and 2) support common, valid use
# cases. Limits are needed since otherwise we could infer infinitely
# complex types.
if (
(partials_new == partials_old)
and (not self.binder.last_pop_changed or iter > 3)
and (widened_new == widened_old or iter > 1)
):
break
partials_old = partials_new
widened_old = widened_new
iter += 1
if iter == 20:
raise RuntimeError("Too many iterations when checking a loop")
self.msg.iteration_dependent_errors(iter_errors)
# If exit_condition is set, assume it must be False on exit from the loop:
if exit_condition:
_, else_map = self.find_isinstance_check(exit_condition)
self.push_type_map(else_map)
# Check the else body:
if else_body:
self.accept(else_body)
#
# Definitions
#
def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
if not self.recurse_into_functions:
return
with self.tscope.function_scope(defn):
self._visit_overloaded_func_def(defn)
def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
num_abstract = 0
if not defn.items:
# In this case we have already complained about none of these being
# valid overloads.
return
if len(defn.items) == 1:
self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn)
if defn.is_property:
# HACK: Infer the type of the property.
assert isinstance(defn.items[0], Decorator)
self.visit_decorator(defn.items[0])
if defn.items[0].var.is_settable_property:
# Perform a reduced visit just to infer the actual setter type.
self.visit_decorator_inner(defn.setter, skip_first_item=True)
setter_type = defn.setter.var.type
# Check if the setter can accept two positional arguments.
any_type = AnyType(TypeOfAny.special_form)
fallback_setter_type = CallableType(
arg_types=[any_type, any_type],
arg_kinds=[ARG_POS, ARG_POS],
arg_names=[None, None],
ret_type=any_type,
fallback=self.named_type("builtins.function"),
)
if setter_type and not is_subtype(setter_type, fallback_setter_type):
self.fail("Invalid property setter signature", defn.setter.func)
setter_type = self.extract_callable_type(setter_type, defn)
if not isinstance(setter_type, CallableType) or len(setter_type.arg_types) != 2:
# TODO: keep precise type for callables with tricky but valid signatures.
setter_type = fallback_setter_type
defn.items[0].var.setter_type = setter_type
if isinstance(defn.type, Overloaded):
# Update legacy property type for decorated properties.
getter_type = self.extract_callable_type(defn.items[0].var.type, defn)
if getter_type is not None:
getter_type.definition = defn.items[0]
defn.type.items[0] = getter_type
for i, fdef in enumerate(defn.items):
assert isinstance(fdef, Decorator)
if defn.is_property:
assert isinstance(defn.items[0], Decorator)
settable = defn.items[0].var.is_settable_property
# Do not visit the second time the items we checked above.
if (settable and i > 1) or (not settable and i > 0):
self.check_func_item(fdef.func, name=fdef.func.name, allow_empty=True)
else:
# Perform full check for real overloads to infer type of all decorated
# overload variants.
self.visit_decorator_inner(fdef, allow_empty=True)
if fdef.func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT):
num_abstract += 1
if num_abstract not in (0, len(defn.items)):
self.fail(message_registry.INCONSISTENT_ABSTRACT_OVERLOAD, defn)
if defn.impl:
with self.enter_overload_impl(defn.impl):
defn.impl.accept(self)
if not defn.is_property:
self.check_overlapping_overloads(defn)
if defn.type is None:
item_types = []
for item in defn.items:
assert isinstance(item, Decorator)
item_type = self.extract_callable_type(item.var.type, item)
if item_type is not None:
item_type.definition = item
item_types.append(item_type)
if item_types:
defn.type = Overloaded(item_types)
elif defn.type is None:
# We store the getter type as an overall overload type, as some
# code paths are getting property type this way.
assert isinstance(defn.items[0], Decorator)
var_type = self.extract_callable_type(defn.items[0].var.type, defn)
if not isinstance(var_type, CallableType):
# Construct a fallback type, invalid types should be already reported.
any_type = AnyType(TypeOfAny.special_form)
var_type = CallableType(
arg_types=[any_type],
arg_kinds=[ARG_POS],
arg_names=[None],
ret_type=any_type,
fallback=self.named_type("builtins.function"),
)
defn.type = Overloaded([var_type])
# Check override validity after we analyzed current definition.
if defn.info:
found_method_base_classes = self.check_method_override(defn)
if (
defn.is_explicit_override
and not found_method_base_classes
and found_method_base_classes is not None
# If the class has Any fallback, we can't be certain that a method
# is really missing - it might come from unfollowed import.
and not defn.info.fallback_to_any
):
self.msg.no_overridable_method(defn.name, defn)
self.check_explicit_override_decorator(defn, found_method_base_classes, defn.impl)
self.check_inplace_operator_method(defn)
@contextmanager
def enter_overload_impl(self, impl: OverloadPart) -> Iterator[None]:
self.overload_impl_stack.append(impl)
try:
yield
finally:
assert self.overload_impl_stack.pop() == impl
def extract_callable_type(self, inner_type: Type | None, ctx: Context) -> CallableType | None:
"""Get type as seen by an overload item caller."""
inner_type = get_proper_type(inner_type)
outer_type: FunctionLike | None = None
if inner_type is None or isinstance(inner_type, AnyType):
return None
if isinstance(inner_type, TypeVarLikeType):
inner_type = get_proper_type(inner_type.upper_bound)
if isinstance(inner_type, TypeType):
inner_type = get_proper_type(
self.expr_checker.analyze_type_type_callee(inner_type.item, ctx)
)
if isinstance(inner_type, FunctionLike):
outer_type = inner_type
elif isinstance(inner_type, Instance):
inner_call = get_proper_type(
analyze_member_access(
name="__call__",
typ=inner_type,
context=ctx,
is_lvalue=False,
is_super=False,
is_operator=True,
original_type=inner_type,
chk=self,
)
)
if isinstance(inner_call, FunctionLike):
outer_type = inner_call
elif isinstance(inner_type, UnionType):
union_type = make_simplified_union(inner_type.items)
if isinstance(union_type, UnionType):
items = []
for item in union_type.items:
callable_item = self.extract_callable_type(item, ctx)
if callable_item is None:
break
items.append(callable_item)
else:
joined_type = get_proper_type(join.join_type_list(items))
if isinstance(joined_type, FunctionLike):
outer_type = joined_type
else:
return self.extract_callable_type(union_type, ctx)
if outer_type is None:
self.msg.not_callable(inner_type, ctx)
return None
if isinstance(outer_type, Overloaded):
return None
assert isinstance(outer_type, CallableType)
return outer_type
def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:
# At this point we should have set the impl already, and all remaining
# items are decorators
if (
self.options.ignore_errors
or self.msg.errors.file in self.msg.errors.ignored_files
or (self.is_typeshed_stub and self.options.test_env)
):
# This is a little hacky, however, the quadratic check here is really expensive, this
# method has no side effects, so we should skip it if we aren't going to report
# anything. In some other places we swallow errors in stubs, but this error is very
# useful for stubs!
return
# Compute some info about the implementation (if it exists) for use below
impl_type: CallableType | None = None
if defn.impl:
if isinstance(defn.impl, FuncDef):
inner_type: Type | None = defn.impl.type
elif isinstance(defn.impl, Decorator):
inner_type = defn.impl.var.type
else:
assert False, "Impl isn't the right type"
# This can happen if we've got an overload with a different
# decorator or if the implementation is untyped -- we gave up on the types.
impl_type = self.extract_callable_type(inner_type, defn.impl)
is_descriptor_get = defn.info and defn.name == "__get__"
for i, item in enumerate(defn.items):
assert isinstance(item, Decorator)
sig1 = self.extract_callable_type(item.var.type, item)
if sig1 is None:
continue
for j, item2 in enumerate(defn.items[i + 1 :]):
assert isinstance(item2, Decorator)
sig2 = self.extract_callable_type(item2.var.type, item2)
if sig2 is None:
continue
if not are_argument_counts_overlapping(sig1, sig2):
continue
if overload_can_never_match(sig1, sig2):
self.msg.overloaded_signature_will_never_match(i + 1, i + j + 2, item2.func)
elif not is_descriptor_get:
# Note: we force mypy to check overload signatures in strict-optional mode
# so we don't incorrectly report errors when a user tries typing an overload
# that happens to have a 'if the argument is None' fallback.
#
# For example, the following is fine in strict-optional mode but would throw
# the unsafe overlap error when strict-optional is disabled:
#
# @overload
# def foo(x: None) -> int: ...
# @overload
# def foo(x: str) -> str: ...
#
# See Python 2's map function for a concrete example of this kind of overload.
current_class = self.scope.active_class()
type_vars = current_class.defn.type_vars if current_class else []
with state.strict_optional_set(True):
if is_unsafe_overlapping_overload_signatures(sig1, sig2, type_vars):
flip_note = (
j == 0
and not is_unsafe_overlapping_overload_signatures(
sig2, sig1, type_vars
)
and not overload_can_never_match(sig2, sig1)
)
self.msg.overloaded_signatures_overlap(
i + 1, i + j + 2, flip_note, item.func
)
if impl_type is not None:
assert defn.impl is not None
# This is what we want from implementation, it should accept all arguments
# of an overload, but the return types should go the opposite way.
if is_callable_compatible(
impl_type,
sig1,
is_compat=is_subtype,
is_proper_subtype=False,
is_compat_return=lambda l, r: is_subtype(r, l),
):
continue
# If the above check didn't work, we repeat some key steps in
# is_callable_compatible() to give a better error message.
# We perform a unification step that's very similar to what
# 'is_callable_compatible' does -- the only difference is that
# we check and see if the impl_type's return value is a
# *supertype* of the overload alternative, not a *subtype*.
#
# This is to match the direction the implementation's return
# needs to be compatible in.
if impl_type.variables:
impl: CallableType | None = unify_generic_callable(
# Normalize both before unifying
impl_type.with_unpacked_kwargs(),
sig1.with_unpacked_kwargs(),
ignore_return=False,
return_constraint_direction=SUPERTYPE_OF,
)
if impl is None:
self.msg.overloaded_signatures_typevar_specific(i + 1, defn.impl)
continue
else:
impl = impl_type
# Prevent extra noise from inconsistent use of @classmethod by copying
# the first arg from the method being checked against.
if sig1.arg_types and defn.info:
impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:])
# Is the overload alternative's arguments subtypes of the implementation's?
if not is_callable_compatible(
impl, sig1, is_compat=is_subtype, is_proper_subtype=False, ignore_return=True
):
self.msg.overloaded_signatures_arg_specific(i + 1, defn.impl)
# Is the overload alternative's return type a subtype of the implementation's?
if not (
is_subtype(sig1.ret_type, impl.ret_type)
or is_subtype(impl.ret_type, sig1.ret_type)
):
self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl)
# Here's the scoop about generators and coroutines.
#
# There are two kinds of generators: classic generators (functions
# with `yield` or `yield from` in the body) and coroutines
# (functions declared with `async def`). The latter are specified
# in PEP 492 and only available in Python >= 3.5.
#
# Classic generators can be parameterized with three types:
# - ty is the Yield type (the type of y in `yield y`)
# - tc is the type reCeived by yield (the type of c in `c = yield`).
# - tr is the Return type (the type of r in `return r`)
#
# A classic generator must define a return type that's either
# `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or
# object or Any). If tc/tr are not given, both are None.
#
# A coroutine must define a return type corresponding to tr; the
# other two are unconstrained. The "external" return type (seen
# by the caller) is Awaitable[tr].
#
# In addition, there's the synthetic type AwaitableGenerator: it
# inherits from both Awaitable and Generator and can be used both
# in `yield from` and in `await`. This type is set automatically
# for functions decorated with `@types.coroutine` or
# `@asyncio.coroutine`. Its single parameter corresponds to tr.
#
# PEP 525 adds a new type, the asynchronous generator, which was
# first released in Python 3.6. Async generators are `async def`
# functions that can also `yield` values. They can be parameterized
# with two types, ty and tc, because they cannot return a value.
#
# There are several useful methods, each taking a type t and a
# flag c indicating whether it's for a generator or coroutine:
#
# - is_generator_return_type(t, c) returns whether t is a Generator,
# Iterator, Iterable (if not c), or Awaitable (if c), or
# AwaitableGenerator (regardless of c).
# - is_async_generator_return_type(t) returns whether t is an
# AsyncGenerator.
# - get_generator_yield_type(t, c) returns ty.
# - get_generator_receive_type(t, c) returns tc.
# - get_generator_return_type(t, c) returns tr.
def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
"""Is `typ` a valid type for a generator/coroutine?
True if `typ` is a *supertype* of Generator or Awaitable.
Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
"""
typ = get_proper_type(typ)
if is_coroutine:
# This means we're in Python 3.5 or later.
at = self.named_generic_type("typing.Awaitable", [AnyType(TypeOfAny.special_form)])
if is_subtype(at, typ):
return True
else:
any_type = AnyType(TypeOfAny.special_form)
gt = self.named_generic_type("typing.Generator", [any_type, any_type, any_type])
if is_subtype(gt, typ):
return True
return isinstance(typ, Instance) and typ.type.fullname == "typing.AwaitableGenerator"
def is_async_generator_return_type(self, typ: Type) -> bool:
"""Is `typ` a valid type for an async generator?
True if `typ` is a supertype of AsyncGenerator.
"""
try:
any_type = AnyType(TypeOfAny.special_form)
agt = self.named_generic_type("typing.AsyncGenerator", [any_type, any_type])
except KeyError:
# we're running on a version of typing that doesn't have AsyncGenerator yet
return False
return is_subtype(agt, typ)
def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given the declared return type of a generator (t), return the type it yields (ty)."""
return_type = get_proper_type(return_type)
if isinstance(return_type, AnyType):
return AnyType(TypeOfAny.from_another_any, source_any=return_type)
elif isinstance(return_type, UnionType):
return make_simplified_union(
[self.get_generator_yield_type(item, is_coroutine) for item in return_type.items]
)
elif not self.is_generator_return_type(
return_type, is_coroutine
) and not self.is_async_generator_return_type(return_type):
# If the function doesn't have a proper Generator (or
# Awaitable) return type, anything is permissible.
return AnyType(TypeOfAny.from_error)
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType(TypeOfAny.from_error)
elif return_type.type.fullname == "typing.Awaitable":
# Awaitable: ty is Any.
return AnyType(TypeOfAny.special_form)
elif return_type.args:
# AwaitableGenerator, Generator, AsyncGenerator, Iterator, or Iterable; ty is args[0].
ret_type = return_type.args[0]
# TODO not best fix, better have dedicated yield token
return ret_type
else:
# If the function's declared supertype of Generator has no type
# parameters (i.e. is `object`), then the yielded values can't
# be accessed so any type is acceptable. IOW, ty is Any.
# (However, see https://github.com/python/mypy/issues/1933)
return AnyType(TypeOfAny.special_form)
def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given a declared generator return type (t), return the type its yield receives (tc)."""
return_type = get_proper_type(return_type)
if isinstance(return_type, AnyType):
return AnyType(TypeOfAny.from_another_any, source_any=return_type)
elif isinstance(return_type, UnionType):
return make_simplified_union(
[self.get_generator_receive_type(item, is_coroutine) for item in return_type.items]
)
elif not self.is_generator_return_type(
return_type, is_coroutine
) and not self.is_async_generator_return_type(return_type):
# If the function doesn't have a proper Generator (or
# Awaitable) return type, anything is permissible.
return AnyType(TypeOfAny.from_error)
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType(TypeOfAny.from_error)
elif return_type.type.fullname == "typing.Awaitable":
# Awaitable, AwaitableGenerator: tc is Any.
return AnyType(TypeOfAny.special_form)
elif (
return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator")
and len(return_type.args) >= 3
):
# Generator: tc is args[1].
return return_type.args[1]
elif return_type.type.fullname == "typing.AsyncGenerator" and len(return_type.args) >= 2:
return return_type.args[1]
else:
# `return_type` is a supertype of Generator, so callers won't be able to send it
# values. IOW, tc is None.
return NoneType()
def get_coroutine_return_type(self, return_type: Type) -> Type:
return_type = get_proper_type(return_type)
if isinstance(return_type, AnyType):
return AnyType(TypeOfAny.from_another_any, source_any=return_type)
assert isinstance(return_type, Instance), "Should only be called on coroutine functions."
# Note: return type is the 3rd type parameter of Coroutine.
return return_type.args[2]
def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given the declared return type of a generator (t), return the type it returns (tr)."""
return_type = get_proper_type(return_type)
if isinstance(return_type, AnyType):
return AnyType(TypeOfAny.from_another_any, source_any=return_type)
elif isinstance(return_type, UnionType):
return make_simplified_union(
[self.get_generator_return_type(item, is_coroutine) for item in return_type.items]
)
elif not self.is_generator_return_type(return_type, is_coroutine):
# If the function doesn't have a proper Generator (or
# Awaitable) return type, anything is permissible.
return AnyType(TypeOfAny.from_error)
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType(TypeOfAny.from_error)
elif return_type.type.fullname == "typing.Awaitable" and len(return_type.args) == 1:
# Awaitable: tr is args[0].
return return_type.args[0]
elif (
return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator")
and len(return_type.args) >= 3
):
# AwaitableGenerator, Generator: tr is args[2].
return return_type.args[2]
else:
# We have a supertype of Generator (Iterator, Iterable, object)
# Treat `Iterator[X]` as a shorthand for `Generator[X, Any, None]`.
return NoneType()
def visit_func_def(self, defn: FuncDef) -> None:
if not self.recurse_into_functions:
return
with self.tscope.function_scope(defn):
self._visit_func_def(defn)
def _visit_func_def(self, defn: FuncDef) -> None:
"""Type check a function definition."""
self.check_func_item(defn, name=defn.name)
if defn.info:
if not defn.is_overload and not defn.is_decorated:
# If the definition is the implementation for an
# overload, the legality of the override has already
# been typechecked, and decorated methods will be
# checked when the decorator is.
found_method_base_classes = self.check_method_override(defn)
self.check_explicit_override_decorator(defn, found_method_base_classes)
self.check_inplace_operator_method(defn)
if defn.original_def:
# Override previous definition.
new_type = self.function_type(defn)
self.check_func_def_override(defn, new_type)
def check_func_item(
self,
defn: FuncItem,
type_override: CallableType | None = None,
name: str | None = None,
allow_empty: bool = False,
) -> None:
"""Type check a function.
If type_override is provided, use it as the function type.
"""
self.dynamic_funcs.append(defn.is_dynamic() and not type_override)
enclosing_node_deferred = self.current_node_deferred
with self.enter_partial_types(is_function=True):
typ = self.function_type(defn)
if type_override:
typ = type_override.copy_modified(line=typ.line, column=typ.column)
if isinstance(typ, CallableType):
with self.enter_attribute_inference_context():
self.check_func_def(defn, typ, name, allow_empty)
else:
raise RuntimeError("Not supported")
self.dynamic_funcs.pop()
self.current_node_deferred = enclosing_node_deferred
if name == "__exit__":
self.check__exit__return_type(defn)
# TODO: the following logic should move to the dataclasses plugin
# https://github.com/python/mypy/issues/15515
if name == "__post_init__":
if dataclasses_plugin.is_processed_dataclass(defn.info):
dataclasses_plugin.check_post_init(self, defn, defn.info)
def check_func_def_override(self, defn: FuncDef, new_type: FunctionLike) -> None:
assert defn.original_def is not None
if isinstance(defn.original_def, FuncDef):
# Function definition overrides function definition.
old_type = self.function_type(defn.original_def)
if not is_same_type(new_type, old_type):
self.msg.incompatible_conditional_function_def(defn, old_type, new_type)
else:
# Function definition overrides a variable initialized via assignment or a
# decorated function.
orig_type = defn.original_def.type
if orig_type is None:
# If other branch is unreachable, we don't type check it and so we might
# not have a type for the original definition
return
if isinstance(orig_type, PartialType):
if orig_type.type is None:
# Ah this is a partial type. Give it the type of the function.
orig_def = defn.original_def
if isinstance(orig_def, Decorator):
var = orig_def.var
else:
var = orig_def
partial_types = self.find_partial_types(var)
if partial_types is not None:
var.type = new_type
del partial_types[var]
else:
# Trying to redefine something like partial empty list as function.
self.fail(message_registry.INCOMPATIBLE_REDEFINITION, defn)
else:
name_expr = NameExpr(defn.name)
name_expr.node = defn.original_def
self.binder.assign_type(name_expr, new_type, orig_type)
self.check_subtype(
new_type,
orig_type,
defn,
message_registry.INCOMPATIBLE_REDEFINITION,
"redefinition with type",
"original type",
)
@contextmanager
def enter_attribute_inference_context(self) -> Iterator[None]:
old_types = self.inferred_attribute_types
self.inferred_attribute_types = {}
yield None
self.inferred_attribute_types = old_types
def check_func_def(
self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False
) -> None:
"""Type check a function definition."""
# Expand type variables with value restrictions to ordinary types.
self.check_typevar_defaults(typ.variables)
expanded = self.expand_typevars(defn, typ)
original_typ = typ
for item, typ in expanded:
old_binder = self.binder
self.binder = ConditionalTypeBinder(self.options)
with self.binder.top_frame_context():
defn.expanded.append(item)
# We may be checking a function definition or an anonymous
# function. In the first case, set up another reference with the
# precise type.
if isinstance(item, FuncDef):
fdef = item
# Check if __init__ has an invalid return type.
if (
fdef.info
and fdef.name in ("__init__", "__init_subclass__")
and not isinstance(
get_proper_type(typ.ret_type), (NoneType, UninhabitedType)
)
and not self.dynamic_funcs[-1]
):
self.fail(
message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item
)
# Check validity of __new__ signature
if fdef.info and fdef.name == "__new__":
self.check___new___signature(fdef, typ)
self.check_for_missing_annotations(fdef)
if self.options.disallow_any_unimported:
if fdef.type and isinstance(fdef.type, CallableType):
ret_type = fdef.type.ret_type
if has_any_from_unimported_type(ret_type):
self.msg.unimported_type_becomes_any("Return type", ret_type, fdef)
for idx, arg_type in enumerate(fdef.type.arg_types):
if has_any_from_unimported_type(arg_type):
prefix = f'Argument {idx + 1} to "{fdef.name}"'
self.msg.unimported_type_becomes_any(prefix, arg_type, fdef)
check_for_explicit_any(
fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef
)
if name: # Special method names
if (
defn.info
and self.is_reverse_op_method(name)
and defn not in self.overload_impl_stack
):
self.check_reverse_op_method(item, typ, name, defn)
elif name in ("__getattr__", "__getattribute__"):
self.check_getattr_method(typ, defn, name)
elif name == "__setattr__":
self.check_setattr_method(typ, defn)
# Refuse contravariant return type variable
if isinstance(typ.ret_type, TypeVarType):
if typ.ret_type.variance == CONTRAVARIANT:
self.fail(
message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT, typ.ret_type
)
self.check_unbound_return_typevar(typ)
elif (
isinstance(original_typ.ret_type, TypeVarType) and original_typ.ret_type.values
):
# Since type vars with values are expanded, the return type is changed
# to a raw value. This is a hack to get it back.
self.check_unbound_return_typevar(original_typ)
# Check that Generator functions have the appropriate return type.
if defn.is_generator:
if defn.is_async_generator:
if not self.is_async_generator_return_type(typ.ret_type):
self.fail(
message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR, typ
)
else:
if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine):
self.fail(message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)
# Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
if defn.is_awaitable_coroutine:
# Update the return type to AwaitableGenerator.
# (This doesn't exist in typing.py, only in typing.pyi.)
t = typ.ret_type
c = defn.is_coroutine
ty = self.get_generator_yield_type(t, c)
tc = self.get_generator_receive_type(t, c)
if c:
tr = self.get_coroutine_return_type(t)
else:
tr = self.get_generator_return_type(t, c)
ret_type = self.named_generic_type(
"typing.AwaitableGenerator", [ty, tc, tr, t]
)
typ = typ.copy_modified(ret_type=ret_type)
defn.type = typ
# Push return type.
self.return_types.append(typ.ret_type)
with self.scope.push_function(defn):
# We temporary push the definition to get the self type as
# visible from *inside* of this function/method.
ref_type: Type | None = self.scope.active_self_type()
if typ.type_is:
arg_index = 0
# For methods and classmethods, we want the second parameter
if ref_type is not None and defn.has_self_or_cls_argument:
arg_index = 1
if arg_index < len(typ.arg_types) and not is_subtype(
typ.type_is, typ.arg_types[arg_index]
):
self.fail(
message_registry.NARROWED_TYPE_NOT_SUBTYPE.format(
format_type(typ.type_is, self.options),
format_type(typ.arg_types[arg_index], self.options),
),
item,
)
# Store argument types.
found_self = False
if isinstance(defn, FuncDef) and not defn.is_decorated:
found_self = self.require_correct_self_argument(typ, defn)
for i in range(len(typ.arg_types)):
arg_type = typ.arg_types[i]
if isinstance(arg_type, TypeVarType):
# Refuse covariant parameter type variables
# TODO: check recursively for inner type variables
if (
arg_type.variance == COVARIANT
and defn.name not in ("__init__", "__new__", "__post_init__")
and not is_private(defn.name) # private methods are not inherited
and (i != 0 or not found_self)
):
ctx: Context = arg_type
if ctx.line < 0:
ctx = typ
self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx)
# Need to store arguments again for the expanded item.
store_argument_type(item, i, typ, self.named_generic_type)
# Type check initialization expressions.
body_is_trivial = is_trivial_body(defn.body)
self.check_default_args(item, body_is_trivial)
# Type check body in a new scope.
with self.binder.top_frame_context():
# Copy some type narrowings from an outer function when it seems safe enough
# (i.e. we can't find an assignment that might change the type of the
# variable afterwards).
new_frame: Frame | None = None
for frame in old_binder.frames:
for key, narrowed_type in frame.types.items():
key_var = extract_var_from_literal_hash(key)
if key_var is not None and not self.is_var_redefined_in_outer_context(
key_var, defn.line
):
# It seems safe to propagate the type narrowing to a nested scope.
if new_frame is None:
new_frame = self.binder.push_frame()
new_frame.types[key] = narrowed_type
self.binder.declarations[key] = old_binder.declarations[key]
if self.options.allow_redefinition_new and not self.is_stub:
# Add formal argument types to the binder.
for arg in defn.arguments:
# TODO: Add these directly using a fast path (possibly "put")
v = arg.variable
if v.type is not None:
n = NameExpr(v.name)
n.node = v
self.binder.assign_type(n, v.type, v.type)
with self.scope.push_function(defn):
# We suppress reachability warnings for empty generator functions
# (return; yield) which have a "yield" that's unreachable by definition
# since it's only there to promote the function into a generator function.
#
# We also suppress reachability warnings when we use TypeVars with value
# restrictions: we only want to report a warning if a certain statement is
# marked as being suppressed in *all* of the expansions, but we currently
# have no good way of doing this.
#
# TODO: Find a way of working around this limitation
if _is_empty_generator_function(item) or len(expanded) >= 2:
self.binder.suppress_unreachable_warnings()
# When checking a third-party library, we can skip function body,
# if during semantic analysis we found that there are no attributes
# defined via self here.
if (
not (
self.options.ignore_errors
or self.msg.errors.file in self.msg.errors.ignored_files
)
or self.options.preserve_asts
or not isinstance(defn, FuncDef)
or defn.has_self_attr_def
):
self.accept(item.body)
unreachable = self.binder.is_unreachable()
if new_frame is not None:
self.binder.pop_frame(True, 0)
if not unreachable:
if defn.is_generator or is_named_instance(
self.return_types[-1], "typing.AwaitableGenerator"
):
return_type = self.get_generator_return_type(
self.return_types[-1], defn.is_coroutine
)
elif defn.is_coroutine:
return_type = self.get_coroutine_return_type(self.return_types[-1])
else:
return_type = self.return_types[-1]
return_type = get_proper_type(return_type)
allow_empty = allow_empty or self.options.allow_empty_bodies
show_error = (
not body_is_trivial
or
# Allow empty bodies for abstract methods, overloads, in tests and stubs.
(
not allow_empty
and not (
isinstance(defn, FuncDef) and defn.abstract_status != NOT_ABSTRACT
)
and not self.is_stub
)
)
# Ignore plugin generated methods, these usually don't need any bodies.
if defn.info is not FUNC_NO_INFO and (
defn.name not in defn.info.names or defn.info.names[defn.name].plugin_generated
):
show_error = False
# Ignore also definitions that appear in `if TYPE_CHECKING: ...` blocks.
# These can't be called at runtime anyway (similar to plugin-generated).
if isinstance(defn, FuncDef) and defn.is_mypy_only:
show_error = False
# We want to minimize the fallout from checking empty bodies
# that was absent in many mypy versions.
if body_is_trivial and is_subtype(NoneType(), return_type):
show_error = False
may_be_abstract = (
body_is_trivial
and defn.info is not FUNC_NO_INFO
and defn.info.metaclass_type is not None
and defn.info.metaclass_type.type.has_base("abc.ABCMeta")
)
if self.options.warn_no_return:
if (
not self.current_node_deferred
and not isinstance(return_type, (NoneType, AnyType))
and show_error
):
# Control flow fell off the end of a function that was
# declared to return a non-None type.
if isinstance(return_type, UninhabitedType):
# This is a NoReturn function
msg = message_registry.INVALID_IMPLICIT_RETURN
else:
msg = message_registry.MISSING_RETURN_STATEMENT
if body_is_trivial:
msg = msg._replace(code=codes.EMPTY_BODY)
self.fail(msg, defn)
if may_be_abstract:
self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)
elif show_error:
msg = message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE
if body_is_trivial:
msg = msg._replace(code=codes.EMPTY_BODY)
# similar to code in check_return_stmt
if (
not self.check_subtype(
subtype_label="implicitly returns",
subtype=NoneType(),
supertype_label="expected",
supertype=return_type,
context=defn,
msg=msg,
)
and may_be_abstract
):
self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)
self.return_types.pop()
self.binder = old_binder
def require_correct_self_argument(self, func: Type, defn: FuncDef) -> bool:
func = get_proper_type(func)
if not isinstance(func, CallableType):
return False
# Do not report errors for untyped methods in classes nested in untyped funcs.
if not (
self.options.check_untyped_defs
or len(self.dynamic_funcs) < 2
or not self.dynamic_funcs[-2]
or not defn.is_dynamic()
):
return bool(func.arg_types)
with self.scope.push_function(defn):
# We temporary push the definition to get the self type as
# visible from *inside* of this function/method.
ref_type: Type | None = self.scope.active_self_type()
if ref_type is None:
return False
if not defn.has_self_or_cls_argument or (
func.arg_kinds and func.arg_kinds[0] in [nodes.ARG_STAR, nodes.ARG_STAR2]
):
return False
if not func.arg_types:
self.fail(
'Method must have at least one argument. Did you forget the "self" argument?', defn
)
return False
arg_type = func.arg_types[0]
if defn.is_class or defn.name == "__new__":
ref_type = mypy.types.TypeType.make_normalized(ref_type)
if is_same_type(arg_type, ref_type):
return True
# This level of erasure matches the one in checkmember.check_self_arg(),
# better keep these two checks consistent.
erased = get_proper_type(erase_typevars(erase_to_bound(arg_type)))
if not is_subtype(ref_type, erased, ignore_type_params=True):
if (
isinstance(erased, Instance)
and erased.type.is_protocol
or isinstance(erased, TypeType)
and isinstance(erased.item, Instance)
and erased.item.type.is_protocol
):
# We allow the explicit self-type to be not a supertype of
# the current class if it is a protocol. For such cases
# the consistency check will be performed at call sites.
msg = None
elif func.arg_names[0] in {"self", "cls"}:
msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(
erased.str_with_options(self.options), ref_type.str_with_options(self.options)
)
else:
msg = message_registry.MISSING_OR_INVALID_SELF_TYPE
if msg:
self.fail(msg, defn)
return True
def is_var_redefined_in_outer_context(self, v: Var, after_line: int) -> bool:
"""Can the variable be assigned to at module top level or outer function?
Note that this doesn't do a full CFG analysis but uses a line number based
heuristic that isn't correct in some (rare) cases.
"""
if v.is_final:
# Final vars are definitely never reassigned.
return False
outers = self.tscope.outer_functions()
if not outers:
# Top-level function -- outer context is top level, and we can't reason about
# globals
return True
for outer in outers:
if isinstance(outer, FuncDef):
if find_last_var_assignment_line(outer.body, v) >= after_line:
return True
return False
def check_unbound_return_typevar(self, typ: CallableType) -> None:
"""Fails when the return typevar is not defined in arguments."""
if isinstance(typ.ret_type, TypeVarType) and typ.ret_type in typ.variables:
arg_type_visitor = CollectArgTypeVarTypes()
for argtype in typ.arg_types:
argtype.accept(arg_type_visitor)
if typ.ret_type not in arg_type_visitor.arg_types:
self.fail(message_registry.UNBOUND_TYPEVAR, typ.ret_type, code=TYPE_VAR)
upper_bound = get_proper_type(typ.ret_type.upper_bound)
if not (
isinstance(upper_bound, Instance)
and upper_bound.type.fullname == "builtins.object"
):
self.note(
"Consider using the upper bound "
f"{format_type(typ.ret_type.upper_bound, self.options)} instead",
context=typ.ret_type,
)
def check_default_args(self, item: FuncItem, body_is_trivial: bool) -> None:
for arg in item.arguments:
if arg.initializer is None:
continue
if body_is_trivial and isinstance(arg.initializer, EllipsisExpr):
continue
name = arg.variable.name
msg = "Incompatible default for "
if name.startswith("__tuple_arg_"):
msg += f"tuple argument {name[12:]}"
else:
msg += f'argument "{name}"'
if (
not self.options.implicit_optional
and isinstance(arg.initializer, NameExpr)
and arg.initializer.fullname == "builtins.None"
):
notes = [
"PEP 484 prohibits implicit Optional. "
"Accordingly, mypy has changed its default to no_implicit_optional=True",
"Use https://github.com/hauntsaninja/no_implicit_optional to automatically "
"upgrade your codebase",
]
else:
notes = None
self.check_simple_assignment(
arg.variable.type,
arg.initializer,
context=arg.initializer,
msg=ErrorMessage(msg, code=codes.ASSIGNMENT),
lvalue_name="argument",
rvalue_name="default",
notes=notes,
)
def is_forward_op_method(self, method_name: str) -> bool:
return method_name in operators.reverse_op_methods
def is_reverse_op_method(self, method_name: str) -> bool:
return method_name in operators.reverse_op_method_set
def check_for_missing_annotations(self, fdef: FuncItem) -> None:
# Check for functions with unspecified/not fully specified types.
def is_unannotated_any(t: Type) -> bool:
if not isinstance(t, ProperType):
return False
return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated
has_explicit_annotation = isinstance(fdef.type, CallableType) and any(
not is_unannotated_any(t) for t in fdef.type.arg_types + [fdef.type.ret_type]
)
show_untyped = not self.is_typeshed_stub or self.options.warn_incomplete_stub
check_incomplete_defs = self.options.disallow_incomplete_defs and has_explicit_annotation
if show_untyped and (self.options.disallow_untyped_defs or check_incomplete_defs):
if fdef.type is None and self.options.disallow_untyped_defs:
if not fdef.arguments or (
len(fdef.arguments) == 1
and (fdef.arg_names[0] == "self" or fdef.arg_names[0] == "cls")
):
self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
if not has_return_statement(fdef) and not fdef.is_generator:
self.note(
'Use "-> None" if function does not return a value',
fdef,
code=codes.NO_UNTYPED_DEF,
)
else:
self.fail(message_registry.FUNCTION_TYPE_EXPECTED, fdef)
elif isinstance(fdef.type, CallableType):
ret_type = get_proper_type(fdef.type.ret_type)
if is_unannotated_any(ret_type):
self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
elif fdef.is_generator:
if is_unannotated_any(
self.get_generator_return_type(ret_type, fdef.is_coroutine)
):
self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
elif fdef.is_coroutine and isinstance(ret_type, Instance):
if is_unannotated_any(self.get_coroutine_return_type(ret_type)):
self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
if any(is_unannotated_any(t) for t in fdef.type.arg_types):
self.fail(message_registry.ARGUMENT_TYPE_EXPECTED, fdef)
def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None:
self_type = fill_typevars_with_any(fdef.info)
bound_type = bind_self(typ, self_type, is_classmethod=True)
# Check that __new__ (after binding cls) returns an instance
# type (or any).
if fdef.info.is_metaclass():
# This is a metaclass, so it must return a new unrelated type.
self.check_subtype(
bound_type.ret_type,
self.type_type(),
fdef,
message_registry.INVALID_NEW_TYPE,
"returns",
"but must return a subtype of",
)
elif not isinstance(
get_proper_type(bound_type.ret_type),
(AnyType, Instance, TupleType, UninhabitedType, LiteralType),
):
self.fail(
message_registry.NON_INSTANCE_NEW_TYPE.format(
format_type(bound_type.ret_type, self.options)
),
fdef,
)
else:
# And that it returns a subtype of the class
self.check_subtype(
bound_type.ret_type,
self_type,
fdef,
message_registry.INVALID_NEW_TYPE,
"returns",
"but must return a subtype of",
)
def check_reverse_op_method(
self, defn: FuncItem, reverse_type: CallableType, reverse_name: str, context: Context
) -> None:
"""Check a reverse operator method such as __radd__."""
# Decides whether it's worth calling check_overlapping_op_methods().
# This used to check for some very obscure scenario. It now
# just decides whether it's worth calling
# check_overlapping_op_methods().
assert defn.info
# First check for a valid signature
method_type = CallableType(
[AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)],
[nodes.ARG_POS, nodes.ARG_POS],
[None, None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
)
if not is_subtype(reverse_type, method_type):
self.msg.invalid_signature(reverse_type, context)
return
if reverse_name in ("__eq__", "__ne__"):
# These are defined for all objects => can't cause trouble.
return
# With 'Any' or 'object' return type we are happy, since any possible
# return value is valid.
ret_type = get_proper_type(reverse_type.ret_type)
if isinstance(ret_type, AnyType):
return
if isinstance(ret_type, Instance):
if ret_type.type.fullname == "builtins.object":
return
if reverse_type.arg_kinds[0] == ARG_STAR:
reverse_type = reverse_type.copy_modified(
arg_types=[reverse_type.arg_types[0]] * 2,
arg_kinds=[ARG_POS] * 2,
arg_names=[reverse_type.arg_names[0], "_"],
)
assert len(reverse_type.arg_types) >= 2
forward_name = operators.normal_from_reverse_op[reverse_name]
forward_inst = get_proper_type(reverse_type.arg_types[1])
if isinstance(forward_inst, TypeVarType):
forward_inst = get_proper_type(forward_inst.upper_bound)
elif isinstance(forward_inst, TupleType):
forward_inst = tuple_fallback(forward_inst)
elif isinstance(forward_inst, (FunctionLike, TypedDictType, LiteralType)):
forward_inst = forward_inst.fallback
if isinstance(forward_inst, TypeType):
item = forward_inst.item
if isinstance(item, Instance):
opt_meta = item.type.metaclass_type
if opt_meta is not None:
forward_inst = opt_meta
def has_readable_member(typ: UnionType | Instance, name: str) -> bool:
# TODO: Deal with attributes of TupleType etc.
if isinstance(typ, Instance):
return typ.type.has_readable_member(name)
return all(
(isinstance(x, UnionType) and has_readable_member(x, name))
or (isinstance(x, Instance) and x.type.has_readable_member(name))
for x in get_proper_types(typ.relevant_items())
)
if not (
isinstance(forward_inst, (Instance, UnionType))
and has_readable_member(forward_inst, forward_name)
):
return
forward_base = reverse_type.arg_types[1]
forward_type = self.expr_checker.analyze_external_member_access(
forward_name, forward_base, context=defn
)
self.check_overlapping_op_methods(
reverse_type,
reverse_name,
defn.info,
forward_type,
forward_name,
forward_base,
context=defn,
)
def check_overlapping_op_methods(
self,
reverse_type: CallableType,
reverse_name: str,
reverse_class: TypeInfo,
forward_type: Type,
forward_name: str,
forward_base: Type,
context: Context,
) -> None:
"""Check for overlapping method and reverse method signatures.
This function assumes that:
- The reverse method has valid argument count and kinds.
- If the reverse operator method accepts some argument of type
X, the forward operator method also belong to class X.
For example, if we have the reverse operator `A.__radd__(B)`, then the
corresponding forward operator must have the type `B.__add__(...)`.
"""
# Note: Suppose we have two operator methods "A.__rOP__(B) -> R1" and
# "B.__OP__(C) -> R2". We check if these two methods are unsafely overlapping
# by using the following algorithm:
#
# 1. Rewrite "B.__OP__(C) -> R1" to "temp1(B, C) -> R1"
#
# 2. Rewrite "A.__rOP__(B) -> R2" to "temp2(B, A) -> R2"
#
# 3. Treat temp1 and temp2 as if they were both variants in the same
# overloaded function. (This mirrors how the Python runtime calls
# operator methods: we first try __OP__, then __rOP__.)
#
# If the first signature is unsafely overlapping with the second,
# report an error.
#
# 4. However, if temp1 shadows temp2 (e.g. the __rOP__ method can never
# be called), do NOT report an error.
#
# This behavior deviates from how we handle overloads -- many of the
# modules in typeshed seem to define __OP__ methods that shadow the
# corresponding __rOP__ method.
#
# Note: we do not attempt to handle unsafe overlaps related to multiple
# inheritance. (This is consistent with how we handle overloads: we also
# do not try checking unsafe overlaps due to multiple inheritance there.)
for forward_item in flatten_nested_unions([forward_type]):
forward_item = get_proper_type(forward_item)
if isinstance(forward_item, CallableType):
if self.is_unsafe_overlapping_op(forward_item, forward_base, reverse_type):
self.msg.operator_method_signatures_overlap(
reverse_class, reverse_name, forward_base, forward_name, context
)
elif isinstance(forward_item, Overloaded):
for item in forward_item.items:
if self.is_unsafe_overlapping_op(item, forward_base, reverse_type):
self.msg.operator_method_signatures_overlap(
reverse_class, reverse_name, forward_base, forward_name, context
)
elif not isinstance(forward_item, AnyType):
self.msg.forward_operator_not_callable(forward_name, context)
def is_unsafe_overlapping_op(
self, forward_item: CallableType, forward_base: Type, reverse_type: CallableType
) -> bool:
# TODO: check argument kinds?
if len(forward_item.arg_types) < 1:
# Not a valid operator method -- can't succeed anyway.
return False
# Erase the type if necessary to make sure we don't have a single
# TypeVar in forward_tweaked. (Having a function signature containing
# just a single TypeVar can lead to unpredictable behavior.)
forward_base_erased = forward_base
if isinstance(forward_base, TypeVarType):
forward_base_erased = erase_to_bound(forward_base)
# Construct normalized function signatures corresponding to the
# operator methods. The first argument is the left operand and the
# second operand is the right argument -- we switch the order of
# the arguments of the reverse method.
# TODO: this manipulation is dangerous if callables are generic.
# Shuffling arguments between callables can create meaningless types.
forward_tweaked = forward_item.copy_modified(
arg_types=[forward_base_erased, forward_item.arg_types[0]],
arg_kinds=[nodes.ARG_POS] * 2,
arg_names=[None] * 2,
)
reverse_tweaked = reverse_type.copy_modified(
arg_types=[reverse_type.arg_types[1], reverse_type.arg_types[0]],
arg_kinds=[nodes.ARG_POS] * 2,
arg_names=[None] * 2,
)
reverse_base_erased = reverse_type.arg_types[0]
if isinstance(reverse_base_erased, TypeVarType):
reverse_base_erased = erase_to_bound(reverse_base_erased)
if is_same_type(reverse_base_erased, forward_base_erased):
return False
elif is_subtype(reverse_base_erased, forward_base_erased):
first = reverse_tweaked
second = forward_tweaked
else:
first = forward_tweaked
second = reverse_tweaked
current_class = self.scope.active_class()
type_vars = current_class.defn.type_vars if current_class else []
return is_unsafe_overlapping_overload_signatures(
first, second, type_vars, partial_only=False
)
def check_inplace_operator_method(self, defn: FuncBase) -> None:
"""Check an inplace operator method such as __iadd__.
They cannot arbitrarily overlap with __add__.
"""
method = defn.name
if method not in operators.inplace_operator_methods:
return
typ = bind_self(self.function_type(defn))
cls = defn.info
other_method = "__" + method[3:]
if cls.has_readable_member(other_method):
instance = fill_typevars(cls)
typ2 = get_proper_type(
self.expr_checker.analyze_external_member_access(other_method, instance, defn)
)
fail = False
if isinstance(typ2, FunctionLike):
if not is_more_general_arg_prefix(typ, typ2):
fail = True
else:
# TODO overloads
fail = True
if fail:
self.msg.signatures_incompatible(method, other_method, defn)
def check_getattr_method(self, typ: Type, context: Context, name: str) -> None:
if len(self.scope.stack) == 1:
# module scope
if name == "__getattribute__":
self.fail(message_registry.MODULE_LEVEL_GETATTRIBUTE, context)
return
# __getattr__ is fine at the module level as of Python 3.7 (PEP 562). We could
# show an error for Python < 3.7, but that would be annoying in code that supports
# both 3.7 and older versions.
method_type = CallableType(
[self.named_type("builtins.str")],
[nodes.ARG_POS],
[None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
)
elif self.scope.active_class():
method_type = CallableType(
[AnyType(TypeOfAny.special_form), self.named_type("builtins.str")],
[nodes.ARG_POS, nodes.ARG_POS],
[None, None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
)
else:
return
if not is_subtype(typ, method_type):
self.msg.invalid_signature_for_special_method(typ, context, name)
def check_setattr_method(self, typ: Type, context: Context) -> None:
if not self.scope.active_class():
return
method_type = CallableType(
[
AnyType(TypeOfAny.special_form),
self.named_type("builtins.str"),
AnyType(TypeOfAny.special_form),
],
[nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],
[None, None, None],
NoneType(),
self.named_type("builtins.function"),
)
if not is_subtype(typ, method_type):
self.msg.invalid_signature_for_special_method(typ, context, "__setattr__")
def check_slots_definition(self, typ: Type, context: Context) -> None:
"""Check the type of __slots__."""
str_type = self.named_type("builtins.str")
expected_type = UnionType(
[str_type, self.named_generic_type("typing.Iterable", [str_type])]
)
self.check_subtype(
typ,
expected_type,
context,
message_registry.INVALID_TYPE_FOR_SLOTS,
"actual type",
"expected type",
code=codes.ASSIGNMENT,
)
def check_match_args(self, var: Var, typ: Type, context: Context) -> None:
"""Check that __match_args__ contains literal strings"""
if not self.scope.active_class():
return
typ = get_proper_type(typ)
if not isinstance(typ, TupleType) or not all(
is_string_literal(item) for item in typ.items
):
self.msg.note(
"__match_args__ must be a tuple containing string literals for checking "
"of match statements to work",
context,
code=codes.LITERAL_REQ,
)
def expand_typevars(
self, defn: FuncItem, typ: CallableType
) -> list[tuple[FuncItem, CallableType]]:
# TODO use generator
subst: list[list[tuple[TypeVarId, Type]]] = []
tvars = list(typ.variables) or []
if defn.info:
# Class type variables
tvars += defn.info.defn.type_vars or []
for tvar in tvars:
if isinstance(tvar, TypeVarType) and tvar.values:
subst.append([(tvar.id, value) for value in tvar.values])
# Make a copy of the function to check for each combination of
# value restricted type variables. (Except when running mypyc,
# where we need one canonical version of the function.)
if subst and not (self.options.mypyc or self.options.inspections):
result: list[tuple[FuncItem, CallableType]] = []
for substitutions in itertools.product(*subst):
mapping = dict(substitutions)
result.append((expand_func(defn, mapping), expand_type(typ, mapping)))
return result
else:
return [(defn, typ)]
def check_explicit_override_decorator(
self,
defn: FuncDef | OverloadedFuncDef,
found_method_base_classes: list[TypeInfo] | None,
context: Context | None = None,
) -> None:
plugin_generated = False
if defn.info and (node := defn.info.get(defn.name)) and node.plugin_generated:
# Do not report issues for plugin generated nodes,
# they can't realistically use `@override` for their methods.
plugin_generated = True
if (
not plugin_generated
and found_method_base_classes
and not defn.is_explicit_override
and defn.name not in ("__init__", "__new__")
and not is_private(defn.name)
):
self.msg.explicit_override_decorator_missing(
defn.name, found_method_base_classes[0].fullname, context or defn
)
def check_method_override(
self, defn: FuncDef | OverloadedFuncDef | Decorator
) -> list[TypeInfo] | None:
"""Check if function definition is compatible with base classes.
This may defer the method if a signature is not available in at least one base class.
Return ``None`` if that happens.
Return a list of base classes which contain an attribute with the method name.
"""
if self.options.ignore_errors or self.msg.errors.file in self.msg.errors.ignored_files:
# Method override checks may be expensive, so skip them in third-party libraries.
return None
# Check against definitions in base classes.
check_override_compatibility = (
defn.name not in ("__init__", "__new__", "__init_subclass__", "__post_init__")
and (self.options.check_untyped_defs or not defn.is_dynamic())
and (
# don't check override for synthesized __replace__ methods from dataclasses
defn.name != "__replace__"
or defn.info.metadata.get("dataclass_tag") is None
)
)
found_method_base_classes: list[TypeInfo] = []
for base in defn.info.mro[1:]:
result = self.check_method_or_accessor_override_for_base(
defn, base, check_override_compatibility
)
if result is None:
# Node was deferred, we will have another attempt later.
return None
if result:
found_method_base_classes.append(base)
return found_method_base_classes
def check_method_or_accessor_override_for_base(
self,
defn: FuncDef | OverloadedFuncDef | Decorator,
base: TypeInfo,
check_override_compatibility: bool,
) -> bool | None:
"""Check if method definition is compatible with a base class.
Return ``None`` if the node was deferred because one of the corresponding
superclass nodes is not ready.
Return ``True`` if an attribute with the method name was found in the base class.
"""
found_base_method = False
if base:
name = defn.name
base_attr = base.names.get(name)
if base_attr:
# First, check if we override a final (always an error, even with Any types).
if is_final_node(base_attr.node) and not is_private(name):
self.msg.cant_override_final(name, base.name, defn)
# Second, final can't override anything writeable independently of types.
if defn.is_final:
self.check_if_final_var_override_writable(name, base_attr.node, defn)
found_base_method = True
if check_override_compatibility:
# Check compatibility of the override signature
# (__init__, __new__, __init_subclass__ are special).
if self.check_method_override_for_base_with_name(defn, name, base):
return None
if name in operators.inplace_operator_methods:
# Figure out the name of the corresponding operator method.
method = "__" + name[3:]
# An inplace operator method such as __iadd__ might not be
# always introduced safely if a base class defined __add__.
# TODO can't come up with an example where this is
# necessary; now it's "just in case"
if self.check_method_override_for_base_with_name(defn, method, base):
return None
return found_base_method
def check_setter_type_override(self, defn: OverloadedFuncDef, base: TypeInfo) -> None:
"""Check override of a setter type of a mutable attribute.
Currently, this should be only called when either base node or the current node
is a custom settable property (i.e. where setter type is different from getter type).
Note that this check is contravariant.
"""
typ, _ = self.node_type_from_base(defn.name, defn.info, defn, setter_type=True)
original_type, _ = self.node_type_from_base(defn.name, base, defn, setter_type=True)
# The caller should handle deferrals.
assert typ is not None and original_type is not None
if not is_subtype(original_type, typ):
self.msg.incompatible_setter_override(defn.setter, typ, original_type, base)
def check_method_override_for_base_with_name(
self, defn: FuncDef | OverloadedFuncDef | Decorator, name: str, base: TypeInfo
) -> bool:
"""Check if overriding an attribute `name` of `base` with `defn` is valid.
Return True if the supertype node was not analysed yet, and `defn` was deferred.
"""
base_attr = base.names.get(name)
if not base_attr:
return False
# The name of the method is defined in the base class.
# Point errors at the 'def' line (important for backward compatibility
# of type ignores).
if not isinstance(defn, Decorator):
context = defn
else:
context = defn.func
# Construct the type of the overriding method.
if isinstance(defn, (FuncDef, OverloadedFuncDef)):
override_class_or_static = defn.is_class or defn.is_static
else:
override_class_or_static = defn.func.is_class or defn.func.is_static
typ, _ = self.node_type_from_base(defn.name, defn.info, defn)
if typ is None:
# This may only happen if we're checking `x-redefinition` member
# and `x` itself is for some reason gone. Normally the node should
# be reachable from the containing class by its name.
# The redefinition is never removed, use this as a sanity check to verify
# the reasoning above.
assert f"{defn.name}-redefinition" in defn.info.names
return False
original_node = base_attr.node
# `original_type` can be partial if (e.g.) it is originally an
# instance variable from an `__init__` block that becomes deferred.
supertype_ready = True
original_type, _ = self.node_type_from_base(name, base, defn)
if original_type is None:
supertype_ready = False
if self.pass_num < self.last_pass:
# If there are passes left, defer this node until next pass,
# otherwise try reconstructing the method type from available information.
# For consistency, defer an enclosing top-level function (if any).
top_level = self.scope.top_level_function()
if isinstance(top_level, FuncDef):
self.defer_node(top_level, self.scope.enclosing_class(top_level))
else:
# Specify enclosing class explicitly, as we check type override before
# entering e.g. decorators or overloads.
self.defer_node(defn, defn.info)
return True
elif isinstance(original_node, (FuncDef, OverloadedFuncDef)):
original_type = self.function_type(original_node)
elif isinstance(original_node, Decorator):
original_type = self.function_type(original_node.func)
elif isinstance(original_node, Var):
# Super type can define method as an attribute.
# See https://github.com/python/mypy/issues/10134
# We also check that sometimes `original_node.type` is None.
# This is the case when we use something like `__hash__ = None`.
if original_node.type is not None:
original_type = get_proper_type(original_node.type)
else:
original_type = NoneType()
else:
# Will always fail to typecheck below, since we know the node is a method
original_type = NoneType()
always_allow_covariant = False
if is_settable_property(defn) and (
is_settable_property(original_node) or isinstance(original_node, Var)
):
if is_custom_settable_property(defn) or (is_custom_settable_property(original_node)):
# Unlike with getter, where we try to construct some fallback type in case of
# deferral during last_pass, we can't make meaningful setter checks if the
# supertype is not known precisely.
if supertype_ready:
always_allow_covariant = True
self.check_setter_type_override(defn, base)
if isinstance(original_node, (FuncDef, OverloadedFuncDef)):
original_class_or_static = original_node.is_class or original_node.is_static
elif isinstance(original_node, Decorator):
fdef = original_node.func
original_class_or_static = fdef.is_class or fdef.is_static
else:
original_class_or_static = False # a variable can't be class or static
typ = get_proper_type(typ)
original_type = get_proper_type(original_type)
if (
is_property(defn)
and isinstance(original_node, Var)
and not original_node.is_final
and (not original_node.is_property or original_node.is_settable_property)
and isinstance(defn, Decorator)
):
# We only give an error where no other similar errors will be given.
if not isinstance(original_type, AnyType):
self.msg.fail(
"Cannot override writeable attribute with read-only property",
# Give an error on function line to match old behaviour.
defn.func,
code=codes.OVERRIDE,
)
if isinstance(original_type, AnyType) or isinstance(typ, AnyType):
pass
elif isinstance(original_type, FunctionLike) and isinstance(typ, FunctionLike):
# Check that the types are compatible.
ok = self.check_override(
typ,
original_type,
defn.name,
name,
base.name if base.module_name == self.tree.fullname else base.fullname,
original_class_or_static,
override_class_or_static,
context,
)
# Check if this override is covariant.
if (
ok
and original_node
and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes
and self.is_writable_attribute(original_node)
and not always_allow_covariant
and not is_subtype(original_type, typ, ignore_pos_arg_names=True)
):
base_str, override_str = format_type_distinctly(
original_type, typ, options=self.options
)
msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg(
f' (base class "{base.name}" defined the type as {base_str},'
f" override has type {override_str})"
)
self.fail(msg, context)
elif isinstance(original_type, UnionType) and any(
is_subtype(typ, orig_typ, ignore_pos_arg_names=True)
for orig_typ in original_type.items
):
# This method is a subtype of at least one union variant.
if (
original_node
and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes
and self.is_writable_attribute(original_node)
and not always_allow_covariant
):
# Covariant override of mutable attribute.
base_str, override_str = format_type_distinctly(
original_type, typ, options=self.options
)
msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg(
f' (base class "{base.name}" defined the type as {base_str},'
f" override has type {override_str})"
)
self.fail(msg, context)
elif is_equivalent(original_type, typ):
# Assume invariance for a non-callable attribute here. Note
# that this doesn't affect read-only properties which can have
# covariant overrides.
pass
elif (
original_node
and (not self.is_writable_attribute(original_node) or always_allow_covariant)
and is_subtype(typ, original_type)
):
# If the attribute is read-only, allow covariance
pass
else:
self.msg.signature_incompatible_with_supertype(
defn.name, name, base.name, context, original=original_type, override=typ
)
return False
def get_op_other_domain(self, tp: FunctionLike) -> Type | None:
if isinstance(tp, CallableType):
if tp.arg_kinds and tp.arg_kinds[0] == ARG_POS:
# For generic methods, domain comparison is tricky, as a first
# approximation erase all remaining type variables.
return erase_typevars(tp.arg_types[0], {v.id for v in tp.variables})
return None
elif isinstance(tp, Overloaded):
raw_items = [self.get_op_other_domain(it) for it in tp.items]
items = [it for it in raw_items if it]
if items:
return make_simplified_union(items)
return None
else:
assert False, "Need to check all FunctionLike subtypes here"
def check_override(
self,
override: FunctionLike,
original: FunctionLike,
name: str,
name_in_super: str,
supertype: str,
original_class_or_static: bool,
override_class_or_static: bool,
node: Context,
) -> bool:
"""Check a method override with given signatures.
Arguments:
override: The signature of the overriding method.
original: The signature of the original supertype method.
name: The name of the overriding method.
Used primarily for generating error messages.
name_in_super: The name of the overridden in the superclass.
Used for generating error messages only.
supertype: The name of the supertype.
original_class_or_static: Indicates whether the original method (from the superclass)
is either a class method or a static method.
override_class_or_static: Indicates whether the overriding method (from the subclass)
is either a class method or a static method.
node: Context node.
"""
# Use boolean variable to clarify code.
fail = False
op_method_wider_note = False
if not is_subtype(override, original, ignore_pos_arg_names=True):
fail = True
elif isinstance(override, Overloaded) and self.is_forward_op_method(name):
# Operator method overrides cannot extend the domain, as
# this could be unsafe with reverse operator methods.
original_domain = self.get_op_other_domain(original)
override_domain = self.get_op_other_domain(override)
if (
original_domain
and override_domain
and not is_subtype(override_domain, original_domain)
):
fail = True
op_method_wider_note = True
if isinstance(override, FunctionLike):
if original_class_or_static and not override_class_or_static:
fail = True
elif isinstance(original, CallableType) and isinstance(override, CallableType):
if original.type_guard is not None and override.type_guard is None:
fail = True
if original.type_is is not None and override.type_is is None:
fail = True
if is_private(name):
fail = False
if fail:
emitted_msg = False
offset_arguments = isinstance(override, CallableType) and override.unpack_kwargs
# Normalize signatures, so we get better diagnostics.
if isinstance(override, (CallableType, Overloaded)):
override = override.with_unpacked_kwargs()
if isinstance(original, (CallableType, Overloaded)):
original = original.with_unpacked_kwargs()
if (
isinstance(override, CallableType)
and isinstance(original, CallableType)
and len(override.arg_types) == len(original.arg_types)
and override.min_args == original.min_args
):
# Give more detailed messages for the common case of both
# signatures having the same number of arguments and no
# overloads.
# override might have its own generic function type
# variables. If an argument or return type of override
# does not have the correct subtyping relationship
# with the original type even after these variables
# are erased, then it is definitely an incompatibility.
override_ids = override.type_var_ids()
type_name = None
definition = get_func_def(override)
if isinstance(definition, FuncDef):
type_name = definition.info.name
def erase_override(t: Type) -> Type:
return erase_typevars(t, ids_to_erase=override_ids)
for i, (sub_kind, super_kind) in enumerate(
zip(override.arg_kinds, original.arg_kinds)
):
if sub_kind.is_positional() and super_kind.is_positional():
override_arg_type = override.arg_types[i]
original_arg_type = original.arg_types[i]
elif sub_kind.is_named() and super_kind.is_named() and not offset_arguments:
arg_name = override.arg_names[i]
if arg_name in original.arg_names:
override_arg_type = override.arg_types[i]
original_i = original.arg_names.index(arg_name)
original_arg_type = original.arg_types[original_i]
else:
continue
else:
continue
if not is_subtype(original_arg_type, erase_override(override_arg_type)):
context: Context = node
if (
isinstance(node, FuncDef)
and not node.is_property
and (
not node.is_decorated # fast path
# allow trivial decorators like @classmethod and @override
or not (sym := node.info.get(node.name))
or not isinstance(sym.node, Decorator)
or not sym.node.decorators
)
):
# If there's any decorator, we can no longer map arguments 1:1 reliably.
arg_node = node.arguments[i + override.bound()]
if arg_node.line != -1:
context = arg_node
self.msg.argument_incompatible_with_supertype(
i + 1,
name,
type_name,
name_in_super,
original_arg_type,
supertype,
context,
secondary_context=node,
)
emitted_msg = True
if not is_subtype(erase_override(override.ret_type), original.ret_type):
self.msg.return_type_incompatible_with_supertype(
name, name_in_super, supertype, original.ret_type, override.ret_type, node
)
emitted_msg = True
elif isinstance(override, Overloaded) and isinstance(original, Overloaded):
# Give a more detailed message in the case where the user is trying to
# override an overload, and the subclass's overload is plausible, except
# that the order of the variants are wrong.
#
# For example, if the parent defines the overload f(int) -> int and f(str) -> str
# (in that order), and if the child swaps the two and does f(str) -> str and
# f(int) -> int
order = []
for child_variant in override.items:
for i, parent_variant in enumerate(original.items):
if is_subtype(child_variant, parent_variant):
order.append(i)
break
if len(order) == len(original.items) and order != sorted(order):
self.msg.overload_signature_incompatible_with_supertype(
name, name_in_super, supertype, node
)
emitted_msg = True
if not emitted_msg:
# Fall back to generic incompatibility message.
self.msg.signature_incompatible_with_supertype(
name, name_in_super, supertype, node, original=original, override=override
)
if op_method_wider_note:
self.note(
"Overloaded operator methods can't have wider argument types in overrides",
node,
code=codes.OVERRIDE,
)
return not fail
def check__exit__return_type(self, defn: FuncItem) -> None:
"""Generate error if the return type of __exit__ is problematic.
If __exit__ always returns False but the return type is declared
as bool, mypy thinks that a with statement may "swallow"
exceptions even though this is not the case, resulting in
invalid reachability inference.
"""
if not defn.type or not isinstance(defn.type, CallableType):
return
ret_type = get_proper_type(defn.type.ret_type)
if not has_bool_item(ret_type):
return
returns = all_return_statements(defn)
if not returns:
return
if all(
isinstance(ret.expr, NameExpr) and ret.expr.fullname == "builtins.False"
for ret in returns
):
self.msg.incorrect__exit__return(defn)
def visit_class_def(self, defn: ClassDef) -> None:
"""Type check a class definition."""
typ = defn.info
for base in typ.mro[1:]:
if base.is_final:
self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn)
if not can_have_shared_disjoint_base(typ.bases):
self.fail(message_registry.INCOMPATIBLE_DISJOINT_BASES.format(typ.name), defn)
with (
self.tscope.class_scope(defn.info),
self.enter_partial_types(is_class=True),
self.enter_class(defn.info),
):
old_binder = self.binder
self.binder = ConditionalTypeBinder(self.options)
with self.binder.top_frame_context():
with self.scope.push_class(defn.info):
self.accept(defn.defs)
self.binder = old_binder
if not (defn.info.typeddict_type or defn.info.tuple_type or defn.info.is_enum):
# If it is not a normal class (not a special form) check class keywords.
self.check_init_subclass(defn)
if not defn.has_incompatible_baseclass:
# Otherwise we've already found errors; more errors are not useful
self.check_multiple_inheritance(typ)
self.check_metaclass_compatibility(typ)
self.check_final_deletable(typ)
if defn.decorators:
sig: Type = type_object_type(defn.info, self.named_type)
# Decorators are applied in reverse order.
for decorator in reversed(defn.decorators):
if isinstance(decorator, CallExpr) and isinstance(
decorator.analyzed, PromoteExpr
):
# _promote is a special type checking related construct.
continue
dec = self.expr_checker.accept(decorator)
temp = self.temp_node(sig, context=decorator)
fullname = None
if isinstance(decorator, RefExpr):
fullname = decorator.fullname or None
# TODO: Figure out how to have clearer error messages.
# (e.g. "class decorator must be a function that accepts a type."
old_allow_abstract_call = self.allow_abstract_call
self.allow_abstract_call = True
sig, _ = self.expr_checker.check_call(
dec, [temp], [nodes.ARG_POS], defn, callable_name=fullname
)
self.allow_abstract_call = old_allow_abstract_call
# TODO: Apply the sig to the actual TypeInfo so we can handle decorators
# that completely swap out the type. (e.g. Callable[[Type[A]], Type[B]])
if typ.defn.type_vars and typ.defn.type_args is None:
for base_inst in typ.bases:
for base_tvar, base_decl_tvar in zip(
base_inst.args, base_inst.type.defn.type_vars
):
if (
isinstance(base_tvar, TypeVarType)
and base_tvar.variance != INVARIANT
and isinstance(base_decl_tvar, TypeVarType)
and base_decl_tvar.variance != base_tvar.variance
):
self.fail(
f'Variance of TypeVar "{base_tvar.name}" incompatible '
"with variance in parent type",
context=defn,
code=codes.TYPE_VAR,
)
if typ.defn.type_vars:
self.check_typevar_defaults(typ.defn.type_vars)
if typ.is_protocol and typ.defn.type_vars:
self.check_protocol_variance(defn)
if not defn.has_incompatible_baseclass and defn.info.is_enum:
self.check_enum(defn)
infer_class_variances(defn.info)
@contextmanager
def enter_class(self, type: TypeInfo) -> Iterator[None]:
original_type = self.type
self.type = type
try:
yield
finally:
self.type = original_type
def check_final_deletable(self, typ: TypeInfo) -> None:
# These checks are only for mypyc. Only perform some checks that are easier
# to implement here than in mypyc.
for attr in typ.deletable_attributes:
node = typ.names.get(attr)
if node and isinstance(node.node, Var) and node.node.is_final:
self.fail(message_registry.CANNOT_MAKE_DELETABLE_FINAL, node.node)
def check_init_subclass(self, defn: ClassDef) -> None:
"""Check that keywords in a class definition are valid arguments for __init_subclass__().
In this example:
1 class Base:
2 def __init_subclass__(cls, thing: int):
3 pass
4 class Child(Base, thing=5):
5 def __init_subclass__(cls):
6 pass
7 Child()
Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here.
Child.__init_subclass__ is never called.
"""
if defn.info.metaclass_type and defn.info.metaclass_type.type.fullname not in (
"builtins.type",
"abc.ABCMeta",
):
# We can't safely check situations when both __init_subclass__ and a custom
# metaclass are present.
return
# At runtime, only Base.__init_subclass__ will be called, so
# we skip the current class itself.
for base in defn.info.mro[1:]:
if "__init_subclass__" not in base.names:
continue
name_expr = NameExpr(defn.name)
name_expr.node = base
callee = MemberExpr(name_expr, "__init_subclass__")
args = list(defn.keywords.values())
arg_names: list[str | None] = list(defn.keywords.keys())
# 'metaclass' keyword is consumed by the rest of the type machinery,
# and is never passed to __init_subclass__ implementations
if "metaclass" in arg_names:
idx = arg_names.index("metaclass")
arg_names.pop(idx)
args.pop(idx)
arg_kinds = [ARG_NAMED] * len(args)
call_expr = CallExpr(callee, args, arg_kinds, arg_names)
call_expr.line = defn.line
call_expr.column = defn.column
call_expr.end_line = defn.end_line
self.expr_checker.accept(call_expr, allow_none_return=True, always_allow_any=True)
# We are only interested in the first Base having __init_subclass__,
# all other bases have already been checked.
break
def check_typevar_defaults(self, tvars: Sequence[TypeVarLikeType]) -> None:
for tv in tvars:
if not (isinstance(tv, TypeVarType) and tv.has_default()):
continue
if not is_subtype(tv.default, tv.upper_bound):
self.fail("TypeVar default must be a subtype of the bound type", tv)
if tv.values and not any(is_same_type(tv.default, value) for value in tv.values):
self.fail("TypeVar default must be one of the constraint types", tv)
def check_enum(self, defn: ClassDef) -> None:
assert defn.info.is_enum
if defn.info.fullname not in ENUM_BASES and "__members__" in defn.info.names:
sym = defn.info.names["__members__"]
if isinstance(sym.node, Var) and sym.node.has_explicit_value:
# `__members__` will always be overwritten by `Enum` and is considered
# read-only so we disallow assigning a value to it
self.fail(message_registry.ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN, sym.node)
for base in defn.info.mro[1:-1]: # we don't need self and `object`
if base.is_enum and base.fullname not in ENUM_BASES:
self.check_final_enum(defn, base)
if self.is_stub and self.tree.fullname not in {"enum", "_typeshed"}:
if not defn.info.enum_members:
self.fail(
f'Detected enum "{defn.info.fullname}" in a type stub with zero members. '
"There is a chance this is due to a recent change in the semantics of "
"enum membership. If so, use `member = value` to mark an enum member, "
"instead of `member: type`",
defn,
)
self.note(
"See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members",
defn,
)
self.check_enum_bases(defn)
self.check_enum_new(defn)
def check_final_enum(self, defn: ClassDef, base: TypeInfo) -> None:
if base.enum_members:
self.fail(f'Cannot extend enum with existing members: "{base.name}"', defn)
def is_final_enum_value(self, sym: SymbolTableNode) -> bool:
if isinstance(sym.node, (FuncBase, Decorator)):
return False # A method is fine
if not isinstance(sym.node, Var):
return True # Can be a class or anything else
# Now, only `Var` is left, we need to check:
# 1. Private name like in `__prop = 1`
# 2. Dunder name like `__hash__ = some_hasher`
# 3. Sunder name like `_order_ = 'a, b, c'`
# 4. If it is a method / descriptor like in `method = classmethod(func)`
if (
is_private(sym.node.name)
or is_dunder(sym.node.name)
or is_sunder(sym.node.name)
# TODO: make sure that `x = @class/staticmethod(func)`
# and `x = property(prop)` both work correctly.
# Now they are incorrectly counted as enum members.
or isinstance(get_proper_type(sym.node.type), FunctionLike)
):
return False
return self.is_stub or sym.node.has_explicit_value
def check_enum_bases(self, defn: ClassDef) -> None:
"""
Non-enum mixins cannot appear after enum bases; this is disallowed at runtime:
class Foo: ...
class Bar(enum.Enum, Foo): ...
But any number of enum mixins can appear in a class definition
(even if multiple enum bases define __new__). So this is fine:
class Foo(enum.Enum):
def __new__(cls, val): ...
class Bar(enum.Enum):
def __new__(cls, val): ...
class Baz(int, Foo, Bar, enum.Flag): ...
"""
enum_base: Instance | None = None
for base in defn.info.bases:
if enum_base is None and base.type.is_enum:
enum_base = base
continue
elif enum_base is not None and not base.type.is_enum:
self.fail(
f'No non-enum mixin classes are allowed after "{enum_base.str_with_options(self.options)}"',
defn,
)
break
def check_enum_new(self, defn: ClassDef) -> None:
def has_new_method(info: TypeInfo) -> bool:
new_method = info.get("__new__")
return bool(
new_method
and new_method.node
and new_method.node.fullname != "builtins.object.__new__"
)
has_new = False
for base in defn.info.bases:
candidate = False
if base.type.is_enum:
# If we have an `Enum`, then we need to check all its bases.
candidate = any(not b.is_enum and has_new_method(b) for b in base.type.mro[1:-1])
else:
candidate = has_new_method(base.type)
if candidate and has_new:
self.fail(
"Only a single data type mixin is allowed for Enum subtypes, "
'found extra "{}"'.format(base.str_with_options(self.options)),
defn,
)
elif candidate:
has_new = True
def check_protocol_variance(self, defn: ClassDef) -> None:
"""Check that protocol definition is compatible with declared
variances of type variables.
Note that we also prohibit declaring protocol classes as invariant
if they are actually covariant/contravariant, since this may break
transitivity of subtyping, see PEP 544.
"""
if defn.type_args is not None:
# Using new-style syntax (PEP 695), so variance will be inferred
return
info = defn.info
object_type = Instance(info.mro[-1], [])
tvars = info.defn.type_vars
if self._variance_dummy_type is None:
_, dummy_info = self.make_fake_typeinfo("<dummy>", "Dummy", "Dummy", [])
self._variance_dummy_type = Instance(dummy_info, [])
dummy = self._variance_dummy_type
for i, tvar in enumerate(tvars):
if not isinstance(tvar, TypeVarType):
# Variance of TypeVarTuple and ParamSpec is underspecified by PEPs.
continue
up_args: list[Type] = [
object_type if i == j else dummy.copy_modified() for j, _ in enumerate(tvars)
]
down_args: list[Type] = [
UninhabitedType() if i == j else dummy.copy_modified() for j, _ in enumerate(tvars)
]
up, down = Instance(info, up_args), Instance(info, down_args)
# TODO: add advanced variance checks for recursive protocols
if is_subtype(down, up, ignore_declared_variance=True):
expected = COVARIANT
elif is_subtype(up, down, ignore_declared_variance=True):
expected = CONTRAVARIANT
else:
expected = INVARIANT
if expected != tvar.variance:
self.msg.bad_proto_variance(tvar.variance, tvar.name, expected, defn)
def check_multiple_inheritance(self, typ: TypeInfo) -> None:
"""Check for multiple inheritance related errors."""
if len(typ.bases) <= 1:
# No multiple inheritance.
return
# Verify that inherited attributes are compatible.
mro = typ.mro[1:]
all_names = {name for base in mro for name in base.names}
for name in sorted(all_names - typ.names.keys()):
# Sort for reproducible message order.
# Attributes defined in both the type and base are skipped.
# Normal checks for attribute compatibility should catch any problems elsewhere.
if is_private(name):
continue
# Compare the first base defining a name with the rest.
# Remaining bases may not be pairwise compatible as the first base provides
# the used definition.
i, base = next((i, base) for i, base in enumerate(mro) if name in base.names)
for base2 in mro[i + 1 :]:
if name in base2.names and base2 not in base.mro:
self.check_compatibility(name, base, base2, typ)
def check_compatibility(
self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: TypeInfo
) -> None:
"""Check if attribute name in base1 is compatible with base2 in multiple inheritance.
Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have
a direct subclass relationship (i.e., the compatibility requirement only derives from
multiple inheritance).
This check verifies that a definition taken from base1 (and mapped to the current
class ctx), is type compatible with the definition taken from base2 (also mapped), so
that unsafe subclassing like this can be detected:
class A(Generic[T]):
def foo(self, x: T) -> None: ...
class B:
def foo(self, x: str) -> None: ...
class C(B, A[int]): ... # this is unsafe because...
x: A[int] = C()
x.foo # ...runtime type is (str) -> None, while static type is (int) -> None
"""
if name in ("__init__", "__new__", "__init_subclass__"):
# __init__ and friends can be incompatible -- it's a special case.
return
first = base1.names[name]
second = base2.names[name]
# Specify current_class explicitly as this function is called after leaving the class.
first_type, _ = self.node_type_from_base(name, base1, ctx, current_class=ctx)
second_type, _ = self.node_type_from_base(name, base2, ctx, current_class=ctx)
# TODO: use more principled logic to decide is_subtype() vs is_equivalent().
# We should rely on mutability of superclass node, not on types being Callable.
# (in particular handle settable properties with setter type different from getter).
p_first_type = get_proper_type(first_type)
p_second_type = get_proper_type(second_type)
if isinstance(p_first_type, FunctionLike) and isinstance(p_second_type, FunctionLike):
if p_first_type.is_type_obj() and p_second_type.is_type_obj():
# For class objects only check the subtype relationship of the classes,
# since we allow incompatible overrides of '__init__'/'__new__'
ok = is_subtype(
left=fill_typevars_with_any(p_first_type.type_object()),
right=fill_typevars_with_any(p_second_type.type_object()),
)
else:
assert first_type and second_type
ok = is_subtype(first_type, second_type, ignore_pos_arg_names=True)
elif first_type and second_type:
if second.node is not None and not self.is_writable_attribute(second.node):
ok = is_subtype(first_type, second_type)
else:
ok = is_equivalent(first_type, second_type)
if ok:
if (
first.node
and second.node
and self.is_writable_attribute(second.node)
and is_property(first.node)
and isinstance(first.node, Decorator)
and not isinstance(p_second_type, AnyType)
):
self.msg.fail(
f'Cannot override writeable attribute "{name}" in base "{base2.name}"'
f' with read-only property in base "{base1.name}"',
ctx,
code=codes.OVERRIDE,
)
else:
if first_type is None:
self.msg.cannot_determine_type_in_base(name, base1.name, ctx)
if second_type is None:
self.msg.cannot_determine_type_in_base(name, base2.name, ctx)
ok = True
# Final attributes can never be overridden, but can override
# non-final read-only attributes.
if is_final_node(second.node) and not is_private(name):
self.msg.cant_override_final(name, base2.name, ctx)
if is_final_node(first.node):
self.check_if_final_var_override_writable(name, second.node, ctx)
# Some attributes like __slots__ and __deletable__ are special, and the type can
# vary across class hierarchy.
if isinstance(second.node, Var) and second.node.allow_incompatible_override:
ok = True
if not ok:
self.msg.base_class_definitions_incompatible(name, base1, base2, ctx)
def check_metaclass_compatibility(self, typ: TypeInfo) -> None:
"""Ensures that metaclasses of all parent types are compatible."""
if (
typ.is_metaclass()
or typ.is_protocol
or typ.is_named_tuple
or typ.is_enum
or typ.typeddict_type is not None
):
return # Reasonable exceptions from this check
if typ.metaclass_type is None and any(
base.type.metaclass_type is not None for base in typ.bases
):
self.fail(
"Metaclass conflict: the metaclass of a derived class must be "
"a (non-strict) subclass of the metaclasses of all its bases",
typ,
code=codes.METACLASS,
)
explanation = typ.explain_metaclass_conflict()
if explanation:
self.note(explanation, typ, code=codes.METACLASS)
def visit_import_from(self, node: ImportFrom) -> None:
for name, _ in node.names:
if (sym := self.globals.get(name)) is not None:
self.warn_deprecated(sym.node, node)
self.check_import(node)
def visit_import_all(self, node: ImportAll) -> None:
self.check_import(node)
def visit_import(self, node: Import) -> None:
self.check_import(node)
def check_import(self, node: ImportBase) -> None:
for assign in node.assignments:
lvalue = assign.lvalues[0]
lvalue_type, _, __ = self.check_lvalue(lvalue)
if lvalue_type is None:
# TODO: This is broken.
lvalue_type = AnyType(TypeOfAny.special_form)
assert isinstance(assign.rvalue, NameExpr)
message = message_registry.INCOMPATIBLE_IMPORT_OF.format(assign.rvalue.name)
self.check_simple_assignment(
lvalue_type,
assign.rvalue,
node,
msg=message,
lvalue_name="local name",
rvalue_name="imported name",
)
#
# Statements
#
def visit_block(self, b: Block) -> None:
if b.is_unreachable:
# This block was marked as being unreachable during semantic analysis.
# It turns out any blocks marked in this way are *intentionally* marked
# as unreachable -- so we don't display an error.
self.binder.unreachable()
return
for s in b.body:
if self.binder.is_unreachable():
if not self.should_report_unreachable_issues():
break
if not self.is_noop_for_reachability(s):
self.msg.unreachable_statement(s)
break
else:
self.accept(s)
# Clear expression cache after each statement to avoid unlimited growth.
self.expr_checker.expr_cache.clear()
def should_report_unreachable_issues(self) -> bool:
return (
self.in_checked_function()
and self.options.warn_unreachable
and not self.current_node_deferred
and not self.binder.is_unreachable_warning_suppressed()
)
def is_noop_for_reachability(self, s: Statement) -> bool:
"""Returns 'true' if the given statement either throws an error of some kind
or is a no-op.
We use this function while handling the '--warn-unreachable' flag. When
that flag is present, we normally report an error on any unreachable statement.
But if that statement is just something like a 'pass' or a just-in-case 'assert False',
reporting an error would be annoying.
"""
if isinstance(s, AssertStmt) and is_false_literal(s.expr):
return True
elif isinstance(s, ReturnStmt) and is_literal_not_implemented(s.expr):
return True
elif isinstance(s, (RaiseStmt, PassStmt)):
return True
elif isinstance(s, ExpressionStmt):
if isinstance(s.expr, EllipsisExpr):
return True
elif isinstance(s.expr, CallExpr):
with self.expr_checker.msg.filter_errors(filter_revealed_type=True):
typ = get_proper_type(
self.expr_checker.accept(
s.expr, allow_none_return=True, always_allow_any=True
)
)
if isinstance(typ, UninhabitedType):
return True
return False
def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
"""Type check an assignment statement.
Handle all kinds of assignment statements (simple, indexed, multiple).
"""
# Avoid type checking type aliases in stubs to avoid false
# positives about modern type syntax available in stubs such
# as X | Y.
if not (s.is_alias_def and self.is_stub):
with self.enter_final_context(s.is_final_def):
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
if s.is_alias_def:
self.check_type_alias_rvalue(s)
if (
s.type is not None
and self.options.disallow_any_unimported
and has_any_from_unimported_type(s.type)
):
if isinstance(s.lvalues[-1], TupleExpr):
# This is a multiple assignment. Instead of figuring out which type is problematic,
# give a generic error message.
self.msg.unimported_type_becomes_any(
"A type on this line", AnyType(TypeOfAny.special_form), s
)
else:
self.msg.unimported_type_becomes_any("Type of variable", s.type, s)
check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)
if len(s.lvalues) > 1:
# Chained assignment (e.g. x = y = ...).
# Make sure that rvalue type will not be reinferred.
if not self.has_type(s.rvalue):
self.expr_checker.accept(s.rvalue)
rvalue = self.temp_node(self.lookup_type(s.rvalue), s)
for lv in s.lvalues[:-1]:
with self.enter_final_context(s.is_final_def):
self.check_assignment(lv, rvalue, s.type is None)
self.check_final(s)
if (
s.is_final_def
and s.type
and not has_no_typevars(s.type)
and self.scope.active_class() is not None
):
self.fail(message_registry.DEPENDENT_FINAL_IN_CLASS_BODY, s)
if s.unanalyzed_type and not self.in_checked_function():
self.msg.annotation_in_unchecked_function(context=s)
def check_type_alias_rvalue(self, s: AssignmentStmt) -> None:
with self.msg.filter_errors():
alias_type = self.expr_checker.accept(s.rvalue)
self.store_type(s.lvalues[-1], alias_type)
def check_assignment(
self,
lvalue: Lvalue,
rvalue: Expression,
infer_lvalue_type: bool = True,
new_syntax: bool = False,
) -> None:
"""Type check a single assignment: lvalue = rvalue."""
if isinstance(lvalue, (TupleExpr, ListExpr)):
self.check_assignment_to_multiple_lvalues(
lvalue.items, rvalue, rvalue, infer_lvalue_type
)
else:
self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, "=")
lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue, rvalue)
# If we're assigning to __getattr__ or similar methods, check that the signature is
# valid.
if isinstance(lvalue, NameExpr) and lvalue.node:
name = lvalue.node.name
if name in ("__setattr__", "__getattribute__", "__getattr__"):
# If an explicit type is given, use that.
if lvalue_type:
signature = lvalue_type
else:
signature = self.expr_checker.accept(rvalue)
if signature:
if name == "__setattr__":
self.check_setattr_method(signature, lvalue)
else:
self.check_getattr_method(signature, lvalue, name)
if name == "__slots__" and self.scope.active_class() is not None:
typ = lvalue_type or self.expr_checker.accept(rvalue)
self.check_slots_definition(typ, lvalue)
if name == "__match_args__" and inferred is not None:
typ = self.expr_checker.accept(rvalue)
self.check_match_args(inferred, typ, lvalue)
if name == "__post_init__":
active_class = self.scope.active_class()
if active_class and dataclasses_plugin.is_processed_dataclass(active_class):
self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue)
if isinstance(lvalue, MemberExpr) and lvalue.name == "__match_args__":
self.fail(message_registry.CANNOT_MODIFY_MATCH_ARGS, lvalue)
if lvalue_type:
if isinstance(lvalue_type, PartialType) and lvalue_type.type is None:
# Try to infer a proper type for a variable with a partial None type.
rvalue_type = self.expr_checker.accept(rvalue)
if isinstance(get_proper_type(rvalue_type), NoneType):
# This doesn't actually provide any additional information -- multiple
# None initializers preserve the partial None type.
return
var = lvalue_type.var
if is_valid_inferred_type(
rvalue_type, self.options, is_lvalue_final=var.is_final
):
partial_types = self.find_partial_types(var)
if partial_types is not None:
if not self.current_node_deferred:
# Partial type can't be final, so strip any literal values.
rvalue_type = remove_instance_last_known_values(rvalue_type)
inferred_type = make_simplified_union([rvalue_type, NoneType()])
self.set_inferred_type(var, lvalue, inferred_type)
else:
var.type = None
del partial_types[var]
lvalue_type = var.type
else:
# Try to infer a partial type.
if not self.infer_partial_type(var, lvalue, rvalue_type):
# If that also failed, give up and let the caller know that we
# cannot read their mind. The definition site will be reported later.
# Calling .put() directly because the newly inferred type is
# not a subtype of None - we are not looking for narrowing
fallback = self.inference_error_fallback_type(rvalue_type)
self.binder.put(lvalue, fallback)
# Same as self.set_inference_error_fallback_type but inlined
# to avoid computing fallback twice.
# We are replacing partial<None> now, so the variable type
# should remain optional.
self.set_inferred_type(var, lvalue, make_optional_type(fallback))
elif (
is_literal_none(rvalue)
and isinstance(lvalue, NameExpr)
and isinstance(lvalue.node, Var)
and lvalue.node.is_initialized_in_class
and not new_syntax
):
# Allow None's to be assigned to class variables with non-Optional types.
rvalue_type = lvalue_type
elif (
isinstance(lvalue, MemberExpr) and lvalue.kind is None
): # Ignore member access to modules
instance_type = self.expr_checker.accept(lvalue.expr)
rvalue_type, lvalue_type, infer_lvalue_type = self.check_member_assignment(
lvalue, instance_type, lvalue_type, rvalue, context=rvalue
)
else:
# Hacky special case for assigning a literal None
# to a variable defined in a previous if
# branch. When we detect this, we'll go back and
# make the type optional. This is somewhat
# unpleasant, and a generalization of this would
# be an improvement!
if (
not self.options.allow_redefinition_new
and is_literal_none(rvalue)
and isinstance(lvalue, NameExpr)
and lvalue.kind == LDEF
and isinstance(lvalue.node, Var)
and lvalue.node.type
and lvalue.node in self.var_decl_frames
and not isinstance(get_proper_type(lvalue_type), AnyType)
):
decl_frame_map = self.var_decl_frames[lvalue.node]
# Check if the nearest common ancestor frame for the definition site
# and the current site is the enclosing frame of an if/elif/else block.
has_if_ancestor = False
for frame in reversed(self.binder.frames):
if frame.id in decl_frame_map:
has_if_ancestor = frame.conditional_frame
break
if has_if_ancestor:
lvalue_type = make_optional_type(lvalue_type)
self.set_inferred_type(lvalue.node, lvalue, lvalue_type)
rvalue_type, lvalue_type = self.check_simple_assignment(
lvalue_type, rvalue, context=rvalue, inferred=inferred, lvalue=lvalue
)
# The above call may update inferred variable type. Prevent further
# inference.
inferred = None
# Special case: only non-abstract non-protocol classes can be assigned to
# variables with explicit type Type[A], where A is protocol or abstract.
p_rvalue_type = get_proper_type(rvalue_type)
p_lvalue_type = get_proper_type(lvalue_type)
if (
isinstance(p_rvalue_type, FunctionLike)
and p_rvalue_type.is_type_obj()
and (
p_rvalue_type.type_object().is_abstract
or p_rvalue_type.type_object().is_protocol
)
and isinstance(p_lvalue_type, TypeType)
and isinstance(p_lvalue_type.item, Instance)
and (
p_lvalue_type.item.type.is_abstract or p_lvalue_type.item.type.is_protocol
)
):
self.msg.concrete_only_assign(p_lvalue_type, rvalue)
return
if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):
# Don't use type binder for definitions of special forms, like named tuples.
if not (isinstance(lvalue, NameExpr) and lvalue.is_special_form):
self.binder.assign_type(lvalue, rvalue_type, lvalue_type)
if (
isinstance(lvalue, NameExpr)
and isinstance(lvalue.node, Var)
and lvalue.node.is_inferred
and lvalue.node.is_index_var
and lvalue_type is not None
):
lvalue.node.type = remove_instance_last_known_values(lvalue_type)
elif (
self.options.allow_redefinition_new
and lvalue_type is not None
and not isinstance(lvalue_type, PartialType)
):
# TODO: Can we use put() here?
self.binder.assign_type(lvalue, lvalue_type, lvalue_type)
elif index_lvalue:
self.check_indexed_assignment(index_lvalue, rvalue, lvalue)
if inferred:
type_context = self.get_variable_type_context(inferred, rvalue)
rvalue_type = self.expr_checker.accept(rvalue, type_context=type_context)
if not (
inferred.is_final
or inferred.is_index_var
or (isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__")
):
rvalue_type = remove_instance_last_known_values(rvalue_type)
self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue)
self.check_assignment_to_slots(lvalue)
if isinstance(lvalue, RefExpr) and not (
isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__"
):
# We check override here at the end after storing the inferred type, since
# override check will try to access the current attribute via symbol tables
# (like a regular attribute access).
self.check_compatibility_all_supers(lvalue, rvalue)
# (type, operator) tuples for augmented assignments supported with partial types
partial_type_augmented_ops: Final = {("builtins.list", "+"), ("builtins.set", "|")}
def get_variable_type_context(self, inferred: Var, rvalue: Expression) -> Type | None:
type_contexts = []
if inferred.info:
for base in inferred.info.mro[1:]:
if inferred.name not in base.names:
continue
# For inference within class body, get supertype attribute as it would look on
# a class object for lambdas overriding methods, etc.
base_node = base.names[inferred.name].node
base_type, _ = self.node_type_from_base(
inferred.name,
base,
inferred,
is_class=is_method(base_node)
or isinstance(base_node, Var)
and not is_instance_var(base_node),
)
if (
base_type
and not (isinstance(base_node, Var) and base_node.invalid_partial_type)
and not isinstance(base_type, PartialType)
):
type_contexts.append(base_type)
# Use most derived supertype as type context if available.
if not type_contexts:
if inferred.name == "__slots__" and self.scope.active_class() is not None:
str_type = self.named_type("builtins.str")
return self.named_generic_type("typing.Iterable", [str_type])
if inferred.name == "__all__" and self.scope.is_top_level():
str_type = self.named_type("builtins.str")
return self.named_generic_type("typing.Sequence", [str_type])
return None
candidate = type_contexts[0]
for other in type_contexts:
if is_proper_subtype(other, candidate):
candidate = other
elif not is_subtype(candidate, other):
# Multiple incompatible candidates, cannot use any of them as context.
return None
return candidate
def try_infer_partial_generic_type_from_assignment(
self, lvalue: Lvalue, rvalue: Expression, op: str
) -> None:
"""Try to infer a precise type for partial generic type from assignment.
'op' is '=' for normal assignment and a binary operator ('+', ...) for
augmented assignment.
Example where this happens:
x = []
if foo():
x = [1] # Infer List[int] as type of 'x'
"""
var = None
if (
isinstance(lvalue, NameExpr)
and isinstance(lvalue.node, Var)
and isinstance(lvalue.node.type, PartialType)
):
var = lvalue.node
elif isinstance(lvalue, MemberExpr):
var = self.expr_checker.get_partial_self_var(lvalue)
if var is not None:
typ = var.type
assert isinstance(typ, PartialType)
if typ.type is None:
return
# Return if this is an unsupported augmented assignment.
if op != "=" and (typ.type.fullname, op) not in self.partial_type_augmented_ops:
return
# TODO: some logic here duplicates the None partial type counterpart
# inlined in check_assignment(), see #8043.
partial_types = self.find_partial_types(var)
if partial_types is None:
return
rvalue_type = self.expr_checker.accept(rvalue)
rvalue_type = get_proper_type(rvalue_type)
if isinstance(rvalue_type, Instance):
if rvalue_type.type == typ.type and is_valid_inferred_type(
rvalue_type, self.options
):
var.type = rvalue_type
del partial_types[var]
elif isinstance(rvalue_type, AnyType):
var.type = fill_typevars_with_any(typ.type)
del partial_types[var]
def check_compatibility_all_supers(self, lvalue: RefExpr, rvalue: Expression) -> None:
lvalue_node = lvalue.node
# Check if we are a class variable with at least one base class
if (
isinstance(lvalue_node, Var)
# If we have explicit annotation, there is no point in checking the override
# for each assignment, so we check only for the first one.
# TODO: for some reason annotated attributes on self are stored as inferred vars.
and (
lvalue_node.line == lvalue.line
or lvalue_node.is_inferred
and not lvalue_node.explicit_self_type
)
and lvalue.kind in (MDEF, None) # None for Vars defined via self
and len(lvalue_node.info.bases) > 0
):
for base in lvalue_node.info.mro[1:]:
tnode = base.names.get(lvalue_node.name)
if tnode is not None:
if not self.check_compatibility_classvar_super(lvalue_node, base, tnode.node):
# Show only one error per variable
break
if not self.check_compatibility_final_super(lvalue_node, base, tnode.node):
# Show only one error per variable
break
direct_bases = lvalue_node.info.direct_base_classes()
last_immediate_base = direct_bases[-1] if direct_bases else None
# The historical behavior for inferred vars was to compare rvalue type against
# the type declared in a superclass. To preserve this behavior, we temporarily
# store the rvalue type on the variable.
actual_lvalue_type = None
if lvalue_node.is_inferred and not lvalue_node.explicit_self_type:
# Don't use partial types as context, similar to regular code path.
ctx = lvalue_node.type if not isinstance(lvalue_node.type, PartialType) else None
rvalue_type = self.expr_checker.accept(rvalue, ctx)
actual_lvalue_type = lvalue_node.type
lvalue_node.type = rvalue_type
lvalue_type, _ = self.node_type_from_base(lvalue_node.name, lvalue_node.info, lvalue)
if lvalue_node.is_inferred and not lvalue_node.explicit_self_type:
lvalue_node.type = actual_lvalue_type
if not lvalue_type:
return
for base in lvalue_node.info.mro[1:]:
# The type of "__slots__" and some other attributes usually doesn't need to
# be compatible with a base class. We'll still check the type of "__slots__"
# against "object" as an exception.
if lvalue_node.allow_incompatible_override and not (
lvalue_node.name == "__slots__" and base.fullname == "builtins.object"
):
continue
if is_private(lvalue_node.name):
continue
base_type, base_node = self.node_type_from_base(lvalue_node.name, base, lvalue)
# TODO: if the r.h.s. is a descriptor, we should check setter override as well.
custom_setter = is_custom_settable_property(base_node)
if isinstance(base_type, PartialType):
base_type = None
if base_type:
assert base_node is not None
if not self.check_compatibility_super(
lvalue_type,
rvalue,
base,
base_type,
base_node,
always_allow_covariant=custom_setter,
):
# Only show one error per variable; even if other
# base classes are also incompatible
return
if lvalue_type and custom_setter:
base_type, _ = self.node_type_from_base(
lvalue_node.name, base, lvalue, setter_type=True
)
# Setter type for a custom property must be ready if
# the getter type is ready.
assert base_type is not None
if not is_subtype(base_type, lvalue_type):
self.msg.incompatible_setter_override(
lvalue, lvalue_type, base_type, base
)
return
if base is last_immediate_base:
# At this point, the attribute was found to be compatible with all
# immediate parents.
break
def check_compatibility_super(
self,
compare_type: Type,
rvalue: Expression,
base: TypeInfo,
base_type: Type,
base_node: Node,
always_allow_covariant: bool,
) -> bool:
# TODO: check __set__() type override for custom descriptors.
# TODO: for descriptors check also class object access override.
ok = self.check_subtype(
compare_type,
base_type,
rvalue,
message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,
"expression has type",
f'base class "{base.name}" defined the type as',
)
if (
ok
and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes
and self.is_writable_attribute(base_node)
and not always_allow_covariant
):
ok = self.check_subtype(
base_type,
compare_type,
rvalue,
message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE,
f'base class "{base.name}" defined the type as',
"expression has type",
)
return ok
def node_type_from_base(
self,
name: str,
base: TypeInfo,
context: Context,
*,
setter_type: bool = False,
is_class: bool = False,
current_class: TypeInfo | None = None,
) -> tuple[Type | None, SymbolNode | None]:
"""Find a type for a name in base class.
Return the type found and the corresponding node defining the name or None
for both if the name is not defined in base or the node type is not known (yet).
The type returned is already properly mapped/bound to the subclass.
If setter_type is True, return setter types for settable properties (otherwise the
getter type is returned).
"""
base_node = base.names.get(name)
# TODO: defer current node if the superclass node is not ready.
if (
not base_node
or isinstance(base_node.node, (Var, Decorator))
and not base_node.type
or isinstance(base_node.type, PartialType)
and base_node.type.type is not None
):
return None, None
if current_class is None:
self_type = self.scope.current_self_type()
else:
self_type = fill_typevars(current_class)
assert self_type is not None, "Internal error: base lookup outside class"
if isinstance(self_type, TupleType):
instance = tuple_fallback(self_type)
else:
instance = self_type
mx = MemberContext(
is_lvalue=setter_type,
is_super=False,
is_operator=mypy.checkexpr.is_operator_method(name),
original_type=self_type,
context=context,
chk=self,
suppress_errors=True,
)
# TODO: we should not filter "cannot determine type" errors here.
with self.msg.filter_errors(filter_deprecated=True):
if is_class:
fallback = instance.type.metaclass_type or mx.named_type("builtins.type")
base_type = analyze_class_attribute_access(
instance, name, mx, mcs_fallback=fallback, override_info=base
)
else:
base_type = analyze_instance_member_access(name, instance, mx, base)
return base_type, base_node.node
def check_compatibility_classvar_super(
self, node: Var, base: TypeInfo, base_node: Node | None
) -> bool:
if not isinstance(base_node, Var):
return True
if node.is_classvar and not base_node.is_classvar:
self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name), node)
return False
elif not node.is_classvar and base_node.is_classvar:
self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name), node)
return False
return True
def check_compatibility_final_super(
self, node: Var, base: TypeInfo, base_node: Node | None
) -> bool:
"""Check if an assignment overrides a final attribute in a base class.
This only checks situations where either a node in base class is not a variable
but a final method, or where override is explicitly declared as final.
In these cases we give a more detailed error message. In addition, we check that
a final variable doesn't override writeable attribute, which is not safe.
Other situations are checked in `check_final()`.
"""
if not isinstance(base_node, (Var, FuncBase, Decorator)):
return True
if is_private(node.name):
return True
if base_node.is_final and (node.is_final or not isinstance(base_node, Var)):
# Give this error only for explicit override attempt with `Final`, or
# if we are overriding a final method with variable.
# Other override attempts will be flagged as assignment to constant
# in `check_final()`.
self.msg.cant_override_final(node.name, base.name, node)
return False
if node.is_final:
if base.fullname in ENUM_BASES or node.name in ENUM_SPECIAL_PROPS:
return True
self.check_if_final_var_override_writable(node.name, base_node, node)
return True
def check_if_final_var_override_writable(
self, name: str, base_node: Node | None, ctx: Context
) -> None:
"""Check that a final variable doesn't override writeable attribute.
This is done to prevent situations like this:
class C:
attr = 1
class D(C):
attr: Final = 2
x: C = D()
x.attr = 3 # Oops!
"""
writable = True
if base_node:
writable = self.is_writable_attribute(base_node)
if writable:
self.msg.final_cant_override_writable(name, ctx)
def get_final_context(self) -> bool:
"""Check whether we a currently checking a final declaration."""
return self._is_final_def
@contextmanager
def enter_final_context(self, is_final_def: bool) -> Iterator[None]:
"""Store whether the current checked assignment is a final declaration."""
old_ctx = self._is_final_def
self._is_final_def = is_final_def
try:
yield
finally:
self._is_final_def = old_ctx
def check_final(self, s: AssignmentStmt | OperatorAssignmentStmt | AssignmentExpr) -> None:
"""Check if this assignment does not assign to a final attribute.
This function performs the check only for name assignments at module
and class scope. The assignments to `obj.attr` and `Cls.attr` are checked
in checkmember.py.
"""
if isinstance(s, AssignmentStmt):
lvs = self.flatten_lvalues(s.lvalues)
elif isinstance(s, AssignmentExpr):
lvs = [s.target]
else:
lvs = [s.lvalue]
is_final_decl = s.is_final_def if isinstance(s, AssignmentStmt) else False
if is_final_decl and (active_class := self.scope.active_class()):
lv = lvs[0]
assert isinstance(lv, RefExpr)
if lv.node is not None:
assert isinstance(lv.node, Var)
if (
lv.node.final_unset_in_class
and not lv.node.final_set_in_init
and not self.is_stub # It is OK to skip initializer in stub files.
and
# Avoid extra error messages, if there is no type in Final[...],
# then we already reported the error about missing r.h.s.
isinstance(s, AssignmentStmt)
and s.type is not None
# Avoid extra error message for NamedTuples,
# they were reported during semanal
and not active_class.is_named_tuple
):
self.msg.final_without_value(s)
for lv in lvs:
if isinstance(lv, RefExpr) and isinstance(lv.node, Var):
name = lv.node.name
cls = self.scope.active_class()
if cls is not None:
# These additional checks exist to give more error messages
# even if the final attribute was overridden with a new symbol
# (which is itself an error)...
for base in cls.mro[1:]:
sym = base.names.get(name)
# We only give this error if base node is variable,
# overriding final method will be caught in
# `check_compatibility_final_super()`.
if sym and isinstance(sym.node, Var):
if sym.node.is_final and not is_final_decl:
self.msg.cant_assign_to_final(name, sym.node.info is None, s)
# ...but only once
break
if lv.node.is_final and not is_final_decl:
self.msg.cant_assign_to_final(name, lv.node.info is None, s)
def check_assignment_to_slots(self, lvalue: Lvalue) -> None:
if not isinstance(lvalue, MemberExpr):
return
inst = get_proper_type(self.expr_checker.accept(lvalue.expr))
if isinstance(inst, TypeVarType) and inst.id.is_self():
# Unwrap self type
inst = get_proper_type(inst.upper_bound)
if not isinstance(inst, Instance):
return
if inst.type.slots is None:
return # Slots do not exist, we can allow any assignment
if lvalue.name in inst.type.slots:
return # We are assigning to an existing slot
for base_info in inst.type.mro[:-1]:
if base_info.names.get("__setattr__") is not None:
# When type has `__setattr__` defined,
# we can assign any dynamic value.
# We exclude object, because it always has `__setattr__`.
return
definition = inst.type.get(lvalue.name)
if definition is None:
# We don't want to duplicate
# `"SomeType" has no attribute "some_attr"`
# error twice.
return
if self.is_assignable_slot(lvalue, definition.type):
return
self.fail(
message_registry.NAME_NOT_IN_SLOTS.format(lvalue.name, inst.type.fullname), lvalue
)
def is_assignable_slot(self, lvalue: Lvalue, typ: Type | None) -> bool:
if getattr(lvalue, "node", None):
return False # This is a definition
typ = get_proper_type(typ)
if typ is None or isinstance(typ, AnyType):
return True # Any can be literally anything, like `@property`
if isinstance(typ, Instance):
# When working with instances, we need to know if they contain
# `__set__` special method. Like `@property` does.
# This makes assigning to properties possible,
# even without extra slot spec.
return typ.type.get("__set__") is not None
if isinstance(typ, FunctionLike):
return True # Can be a property, or some other magic
if isinstance(typ, UnionType):
return all(self.is_assignable_slot(lvalue, u) for u in typ.items)
return False
def flatten_rvalues(self, rvalues: list[Expression]) -> list[Expression]:
"""Flatten expression list by expanding those * items that have tuple type.
For each regular type item in the tuple type use a TempNode(), for an Unpack
item use a corresponding StarExpr(TempNode()).
"""
new_rvalues = []
for rv in rvalues:
if not isinstance(rv, StarExpr):
new_rvalues.append(rv)
continue
typ = get_proper_type(self.expr_checker.accept(rv.expr))
if not isinstance(typ, TupleType):
new_rvalues.append(rv)
continue
for t in typ.items:
if not isinstance(t, UnpackType):
new_rvalues.append(TempNode(t))
else:
unpacked = get_proper_type(t.type)
if isinstance(unpacked, TypeVarTupleType):
fallback = unpacked.upper_bound
else:
assert (
isinstance(unpacked, Instance)
and unpacked.type.fullname == "builtins.tuple"
)
fallback = unpacked
new_rvalues.append(StarExpr(TempNode(fallback)))
return new_rvalues
def check_assignment_to_multiple_lvalues(
self,
lvalues: list[Lvalue],
rvalue: Expression,
context: Context,
infer_lvalue_type: bool = True,
) -> None:
if isinstance(rvalue, (TupleExpr, ListExpr)):
# Recursively go into Tuple or List expression rhs instead of
# using the type of rhs, because this allows more fine-grained
# control in cases like: a, b = [int, str] where rhs would get
# type List[object]
rvalues: list[Expression] = []
iterable_type: Type | None = None
last_idx: int | None = None
for idx_rval, rval in enumerate(self.flatten_rvalues(rvalue.items)):
if isinstance(rval, StarExpr):
typs = get_proper_type(self.expr_checker.accept(rval.expr))
if self.type_is_iterable(typs) and isinstance(typs, Instance):
if iterable_type is not None and iterable_type != self.iterable_item_type(
typs, rvalue
):
self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)
else:
if last_idx is None or last_idx + 1 == idx_rval:
rvalues.append(rval)
last_idx = idx_rval
iterable_type = self.iterable_item_type(typs, rvalue)
else:
self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)
else:
self.fail(message_registry.ITERABLE_TYPE_EXPECTED.format(typs), context)
else:
rvalues.append(rval)
iterable_start: int | None = None
iterable_end: int | None = None
for i, rval in enumerate(rvalues):
if isinstance(rval, StarExpr):
typs = get_proper_type(self.expr_checker.accept(rval.expr))
if self.type_is_iterable(typs) and isinstance(typs, Instance):
if iterable_start is None:
iterable_start = i
iterable_end = i
if (
iterable_start is not None
and iterable_end is not None
and iterable_type is not None
):
iterable_num = iterable_end - iterable_start + 1
rvalue_needed = len(lvalues) - (len(rvalues) - iterable_num)
if rvalue_needed > 0:
rvalues = (
rvalues[0:iterable_start]
+ [TempNode(iterable_type, context=rval) for _ in range(rvalue_needed)]
+ rvalues[iterable_end + 1 :]
)
if self.check_rvalue_count_in_assignment(lvalues, len(rvalues), context):
star_index = next(
(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
)
left_lvs = lvalues[:star_index]
star_lv = (
cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
)
right_lvs = lvalues[star_index + 1 :]
left_rvs, star_rvs, right_rvs = self.split_around_star(
rvalues, star_index, len(lvalues)
)
lr_pairs = list(zip(left_lvs, left_rvs))
if star_lv:
rv_list = ListExpr(star_rvs)
rv_list.set_line(rvalue)
lr_pairs.append((star_lv.expr, rv_list))
lr_pairs.extend(zip(right_lvs, right_rvs))
for lv, rv in lr_pairs:
self.check_assignment(lv, rv, infer_lvalue_type)
else:
self.check_multi_assignment(lvalues, rvalue, context, infer_lvalue_type)
def check_rvalue_count_in_assignment(
self,
lvalues: list[Lvalue],
rvalue_count: int,
context: Context,
rvalue_unpack: int | None = None,
) -> bool:
if rvalue_unpack is not None:
if not any(isinstance(e, StarExpr) for e in lvalues):
self.fail("Variadic tuple unpacking requires a star target", context)
return False
if len(lvalues) > rvalue_count:
self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context)
return False
left_star_index = next(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr))
left_prefix = left_star_index
left_suffix = len(lvalues) - left_star_index - 1
right_prefix = rvalue_unpack
right_suffix = rvalue_count - rvalue_unpack - 1
if left_suffix > right_suffix or left_prefix > right_prefix:
# Case of asymmetric unpack like:
# rv: tuple[int, *Ts, int, int]
# x, y, *xs, z = rv
# it is technically valid, but is tricky to reason about.
# TODO: support this (at least if the r.h.s. unpack is a homogeneous tuple).
self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context)
return True
if any(isinstance(lvalue, StarExpr) for lvalue in lvalues):
if len(lvalues) - 1 > rvalue_count:
self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues) - 1, context)
return False
elif rvalue_count != len(lvalues):
self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues), context)
return False
return True
def check_multi_assignment(
self,
lvalues: list[Lvalue],
rvalue: Expression,
context: Context,
infer_lvalue_type: bool = True,
rv_type: Type | None = None,
undefined_rvalue: bool = False,
) -> None:
"""Check the assignment of one rvalue to a number of lvalues."""
# Infer the type of an ordinary rvalue expression.
# TODO: maybe elsewhere; redundant.
rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue))
if isinstance(rvalue_type, TypeVarLikeType):
rvalue_type = get_proper_type(rvalue_type.upper_bound)
if isinstance(rvalue_type, UnionType):
# If this is an Optional type in non-strict Optional code, unwrap it.
relevant_items = rvalue_type.relevant_items()
if len(relevant_items) == 1:
rvalue_type = get_proper_type(relevant_items[0])
if (
isinstance(rvalue_type, TupleType)
and find_unpack_in_list(rvalue_type.items) is not None
):
# Normalize for consistent handling with "old-style" homogeneous tuples.
rvalue_type = expand_type(rvalue_type, {})
if isinstance(rvalue_type, AnyType):
for lv in lvalues:
if isinstance(lv, StarExpr):
lv = lv.expr
temp_node = self.temp_node(
AnyType(TypeOfAny.from_another_any, source_any=rvalue_type), context
)
self.check_assignment(lv, temp_node, infer_lvalue_type)
elif isinstance(rvalue_type, TupleType):
self.check_multi_assignment_from_tuple(
lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type
)
elif isinstance(rvalue_type, UnionType):
self.check_multi_assignment_from_union(
lvalues, rvalue, rvalue_type, context, infer_lvalue_type
)
elif isinstance(rvalue_type, Instance) and rvalue_type.type.fullname == "builtins.str":
self.msg.unpacking_strings_disallowed(context)
else:
self.check_multi_assignment_from_iterable(
lvalues, rvalue_type, context, infer_lvalue_type
)
def check_multi_assignment_from_union(
self,
lvalues: list[Expression],
rvalue: Expression,
rvalue_type: UnionType,
context: Context,
infer_lvalue_type: bool,
) -> None:
"""Check assignment to multiple lvalue targets when rvalue type is a Union[...].
For example:
t: Union[Tuple[int, int], Tuple[str, str]]
x, y = t
reveal_type(x) # Union[int, str]
The idea in this case is to process the assignment for every item of the union.
Important note: the types are collected in two places, 'union_types' contains
inferred types for first assignments, 'assignments' contains the narrowed types
for binder.
"""
self.no_partial_types = True
transposed: tuple[list[Type], ...] = tuple([] for _ in self.flatten_lvalues(lvalues))
# Notify binder that we want to defer bindings and instead collect types.
with self.binder.accumulate_type_assignments() as assignments:
for item in rvalue_type.items:
# Type check the assignment separately for each union item and collect
# the inferred lvalue types for each union item.
self.check_multi_assignment(
lvalues,
rvalue,
context,
infer_lvalue_type=infer_lvalue_type,
rv_type=item,
undefined_rvalue=True,
)
for t, lv in zip(transposed, self.flatten_lvalues(lvalues)):
# We can access _type_maps directly since temporary type maps are
# only created within expressions.
t.append(self._type_maps[-1].pop(lv, AnyType(TypeOfAny.special_form)))
union_types = tuple(make_simplified_union(col) for col in transposed)
for expr, items in assignments.items():
# Bind a union of types collected in 'assignments' to every expression.
if isinstance(expr, StarExpr):
expr = expr.expr
# TODO: See comment in binder.py, ConditionalTypeBinder.assign_type
# It's unclear why the 'declared_type' param is sometimes 'None'
clean_items: list[tuple[Type, Type]] = []
for type, declared_type in items:
assert declared_type is not None
clean_items.append((type, declared_type))
types, declared_types = zip(*clean_items)
self.binder.assign_type(
expr,
make_simplified_union(list(types)),
make_simplified_union(list(declared_types)),
)
for union, lv in zip(union_types, self.flatten_lvalues(lvalues)):
# Properly store the inferred types.
_1, _2, inferred = self.check_lvalue(lv)
if inferred:
self.set_inferred_type(inferred, lv, union)
else:
self.store_type(lv, union)
self.no_partial_types = False
def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]:
res: list[Expression] = []
for lv in lvalues:
if isinstance(lv, (TupleExpr, ListExpr)):
res.extend(self.flatten_lvalues(lv.items))
if isinstance(lv, StarExpr):
# Unwrap StarExpr, since it is unwrapped by other helpers.
lv = lv.expr
res.append(lv)
return res
def check_multi_assignment_from_tuple(
self,
lvalues: list[Lvalue],
rvalue: Expression,
rvalue_type: TupleType,
context: Context,
undefined_rvalue: bool,
infer_lvalue_type: bool = True,
) -> None:
rvalue_unpack = find_unpack_in_list(rvalue_type.items)
if self.check_rvalue_count_in_assignment(
lvalues, len(rvalue_type.items), context, rvalue_unpack=rvalue_unpack
):
star_index = next(
(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
)
left_lvs = lvalues[:star_index]
star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
right_lvs = lvalues[star_index + 1 :]
if not undefined_rvalue:
# Infer rvalue again, now in the correct type context.
lvalue_type = self.lvalue_type_for_inference(lvalues, rvalue_type)
reinferred_rvalue_type = get_proper_type(
self.expr_checker.accept(rvalue, lvalue_type)
)
if isinstance(reinferred_rvalue_type, TypeVarLikeType):
reinferred_rvalue_type = get_proper_type(reinferred_rvalue_type.upper_bound)
if isinstance(reinferred_rvalue_type, UnionType):
# If this is an Optional type in non-strict Optional code, unwrap it.
relevant_items = reinferred_rvalue_type.relevant_items()
if len(relevant_items) == 1:
reinferred_rvalue_type = get_proper_type(relevant_items[0])
if isinstance(reinferred_rvalue_type, UnionType):
self.check_multi_assignment_from_union(
lvalues, rvalue, reinferred_rvalue_type, context, infer_lvalue_type
)
return
if isinstance(reinferred_rvalue_type, AnyType):
# We can get Any if the current node is
# deferred. Doing more inference in deferred nodes
# is hard, so give up for now. We can also get
# here if reinferring types above changes the
# inferred return type for an overloaded function
# to be ambiguous.
return
assert isinstance(reinferred_rvalue_type, TupleType)
rvalue_type = reinferred_rvalue_type
left_rv_types, star_rv_types, right_rv_types = self.split_around_star(
rvalue_type.items, star_index, len(lvalues)
)
for lv, rv_type in zip(left_lvs, left_rv_types):
self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)
if star_lv:
list_expr = ListExpr(
[
(
self.temp_node(rv_type, context)
if not isinstance(rv_type, UnpackType)
else StarExpr(self.temp_node(rv_type.type, context))
)
for rv_type in star_rv_types
]
)
list_expr.set_line(context)
self.check_assignment(star_lv.expr, list_expr, infer_lvalue_type)
for lv, rv_type in zip(right_lvs, right_rv_types):
self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)
else:
# Store meaningful Any types for lvalues, errors are already given
# by check_rvalue_count_in_assignment()
if infer_lvalue_type:
for lv in lvalues:
if (
isinstance(lv, NameExpr)
and isinstance(lv.node, Var)
and lv.node.type is None
):
lv.node.type = AnyType(TypeOfAny.from_error)
elif isinstance(lv, StarExpr):
if (
isinstance(lv.expr, NameExpr)
and isinstance(lv.expr.node, Var)
and lv.expr.node.type is None
):
lv.expr.node.type = self.named_generic_type(
"builtins.list", [AnyType(TypeOfAny.from_error)]
)
def lvalue_type_for_inference(self, lvalues: list[Lvalue], rvalue_type: TupleType) -> Type:
star_index = next(
(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
)
left_lvs = lvalues[:star_index]
star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
right_lvs = lvalues[star_index + 1 :]
left_rv_types, star_rv_types, right_rv_types = self.split_around_star(
rvalue_type.items, star_index, len(lvalues)
)
type_parameters: list[Type] = []
def append_types_for_inference(lvs: list[Expression], rv_types: list[Type]) -> None:
for lv, rv_type in zip(lvs, rv_types):
sub_lvalue_type, index_expr, inferred = self.check_lvalue(lv)
if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):
type_parameters.append(sub_lvalue_type)
else: # index lvalue
# TODO Figure out more precise type context, probably
# based on the type signature of the _set method.
type_parameters.append(rv_type)
append_types_for_inference(left_lvs, left_rv_types)
if star_lv:
sub_lvalue_type, index_expr, inferred = self.check_lvalue(star_lv.expr)
if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):
type_parameters.extend([sub_lvalue_type] * len(star_rv_types))
else: # index lvalue
# TODO Figure out more precise type context, probably
# based on the type signature of the _set method.
type_parameters.extend(star_rv_types)
append_types_for_inference(right_lvs, right_rv_types)
return TupleType(type_parameters, self.named_type("builtins.tuple"))
def split_around_star(
self, items: list[T], star_index: int, length: int
) -> tuple[list[T], list[T], list[T]]:
"""Splits a list of items in three to match another list of length 'length'
that contains a starred expression at 'star_index' in the following way:
star_index = 2, length = 5 (i.e., [a,b,*,c,d]), items = [1,2,3,4,5,6,7]
returns in: ([1,2], [3,4,5], [6,7])
"""
nr_right_of_star = length - star_index - 1
right_index = -nr_right_of_star if nr_right_of_star != 0 else len(items)
left = items[:star_index]
star = items[star_index:right_index]
right = items[right_index:]
return left, star, right
def type_is_iterable(self, type: Type) -> bool:
type = get_proper_type(type)
if isinstance(type, FunctionLike) and type.is_type_obj():
type = type.fallback
return is_subtype(
type, self.named_generic_type("typing.Iterable", [AnyType(TypeOfAny.special_form)])
)
def check_multi_assignment_from_iterable(
self,
lvalues: list[Lvalue],
rvalue_type: Type,
context: Context,
infer_lvalue_type: bool = True,
) -> None:
rvalue_type = get_proper_type(rvalue_type)
if self.type_is_iterable(rvalue_type) and isinstance(
rvalue_type, (Instance, CallableType, TypeType, Overloaded)
):
item_type = self.iterable_item_type(rvalue_type, context)
for lv in lvalues:
if isinstance(lv, StarExpr):
items_type = self.named_generic_type("builtins.list", [item_type])
self.check_assignment(
lv.expr, self.temp_node(items_type, context), infer_lvalue_type
)
else:
self.check_assignment(
lv, self.temp_node(item_type, context), infer_lvalue_type
)
else:
self.msg.type_not_iterable(rvalue_type, context)
def check_lvalue(
self, lvalue: Lvalue, rvalue: Expression | None = None
) -> tuple[Type | None, IndexExpr | None, Var | None]:
lvalue_type = None
index_lvalue = None
inferred = None
if self.is_definition(lvalue) and (
not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)
):
if isinstance(lvalue, NameExpr):
assert isinstance(lvalue.node, Var)
inferred = lvalue.node
else:
assert isinstance(lvalue, MemberExpr)
self.expr_checker.accept(lvalue.expr)
inferred = lvalue.def_var
elif isinstance(lvalue, IndexExpr):
index_lvalue = lvalue
elif isinstance(lvalue, MemberExpr):
lvalue_type = self.expr_checker.analyze_ordinary_member_access(lvalue, True, rvalue)
self.store_type(lvalue, lvalue_type)
elif isinstance(lvalue, NameExpr):
lvalue_type = self.expr_checker.analyze_ref_expr(lvalue, lvalue=True)
if (
self.options.allow_redefinition_new
and isinstance(lvalue.node, Var)
and lvalue.node.is_inferred
):
inferred = lvalue.node
self.store_type(lvalue, lvalue_type)
elif isinstance(lvalue, (TupleExpr, ListExpr)):
types = [
self.check_lvalue(sub_expr)[0] or
# This type will be used as a context for further inference of rvalue,
# we put Uninhabited if there is no information available from lvalue.
UninhabitedType()
for sub_expr in lvalue.items
]
lvalue_type = TupleType(types, self.named_type("builtins.tuple"))
elif isinstance(lvalue, StarExpr):
lvalue_type, _, _ = self.check_lvalue(lvalue.expr)
else:
lvalue_type = self.expr_checker.accept(lvalue)
return lvalue_type, index_lvalue, inferred
def is_definition(self, s: Lvalue) -> bool:
if isinstance(s, NameExpr):
if s.is_inferred_def:
return True
# If the node type is not defined, this must the first assignment
# that we process => this is a definition, even though the semantic
# analyzer did not recognize this as such. This can arise in code
# that uses isinstance checks, if type checking of the primary
# definition is skipped due to an always False type check.
node = s.node
if isinstance(node, Var):
return node.type is None
elif isinstance(s, MemberExpr):
return s.is_inferred_def
return False
def infer_variable_type(
self, name: Var, lvalue: Lvalue, init_type: Type, context: Context
) -> None:
"""Infer the type of initialized variables from initializer type."""
if isinstance(init_type, DeletedType):
self.msg.deleted_as_rvalue(init_type, context)
elif (
not is_valid_inferred_type(
init_type,
self.options,
is_lvalue_final=name.is_final,
is_lvalue_member=isinstance(lvalue, MemberExpr),
)
and not self.no_partial_types
):
# We cannot use the type of the initialization expression for full type
# inference (it's not specific enough), but we might be able to give
# partial type which will be made more specific later. A partial type
# gets generated in assignment like 'x = []' where item type is not known.
if name.name != "_" and not self.infer_partial_type(name, lvalue, init_type):
self.msg.need_annotation_for_var(name, context, self.options)
self.set_inference_error_fallback_type(name, lvalue, init_type)
elif (
isinstance(lvalue, MemberExpr)
and self.inferred_attribute_types is not None
and lvalue.def_var
and lvalue.def_var in self.inferred_attribute_types
and not is_same_type(self.inferred_attribute_types[lvalue.def_var], init_type)
):
# Multiple, inconsistent types inferred for an attribute.
self.msg.need_annotation_for_var(name, context, self.options)
name.type = AnyType(TypeOfAny.from_error)
else:
# Infer type of the target.
# Make the type more general (strip away function names etc.).
init_type = strip_type(init_type)
self.set_inferred_type(name, lvalue, init_type)
if self.options.allow_redefinition_new:
self.binder.assign_type(lvalue, init_type, init_type)
def infer_partial_type(self, name: Var, lvalue: Lvalue, init_type: Type) -> bool:
init_type = get_proper_type(init_type)
if isinstance(init_type, NoneType) and (
isinstance(lvalue, MemberExpr) or not self.options.allow_redefinition_new
):
# When using --allow-redefinition-new, None types aren't special
# when inferring simple variable types.
partial_type = PartialType(None, name)
elif isinstance(init_type, Instance):
fullname = init_type.type.fullname
is_ref = isinstance(lvalue, RefExpr)
if (
is_ref
and (
fullname == "builtins.list"
or fullname == "builtins.set"
or fullname == "builtins.dict"
or fullname == "collections.OrderedDict"
)
and all(
isinstance(t, (NoneType, UninhabitedType))
for t in get_proper_types(init_type.args)
)
):
partial_type = PartialType(init_type.type, name)
elif is_ref and fullname == "collections.defaultdict":
arg0 = get_proper_type(init_type.args[0])
arg1 = get_proper_type(init_type.args[1])
if isinstance(
arg0, (NoneType, UninhabitedType)
) and self.is_valid_defaultdict_partial_value_type(arg1):
arg1 = erase_type(arg1)
assert isinstance(arg1, Instance)
partial_type = PartialType(init_type.type, name, arg1)
else:
return False
else:
return False
else:
return False
self.set_inferred_type(name, lvalue, partial_type)
self.partial_types[-1].map[name] = lvalue
return True
def is_valid_defaultdict_partial_value_type(self, t: ProperType) -> bool:
"""Check if t can be used as the basis for a partial defaultdict value type.
Examples:
* t is 'int' --> True
* t is 'list[Never]' --> True
* t is 'dict[...]' --> False (only generic types with a single type
argument supported)
"""
if not isinstance(t, Instance):
return False
if len(t.args) == 0:
return True
if len(t.args) == 1:
arg = get_proper_type(t.args[0])
if self.options.old_type_inference:
# Allow leaked TypeVars for legacy inference logic.
allowed = isinstance(arg, (UninhabitedType, NoneType, TypeVarType))
else:
allowed = isinstance(arg, (UninhabitedType, NoneType))
if allowed:
return True
return False
def set_inferred_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:
"""Store inferred variable type.
Store the type to both the variable node and the expression node that
refers to the variable (lvalue). If var is None, do nothing.
"""
if var and not self.current_node_deferred:
var.type = type
var.is_inferred = True
var.is_ready = True
if var not in self.var_decl_frames:
# Used for the hack to improve optional type inference in conditionals
self.var_decl_frames[var] = {frame.id for frame in self.binder.frames}
if isinstance(lvalue, MemberExpr) and self.inferred_attribute_types is not None:
# Store inferred attribute type so that we can check consistency afterwards.
if lvalue.def_var is not None:
self.inferred_attribute_types[lvalue.def_var] = type
self.store_type(lvalue, type)
p_type = get_proper_type(type)
definition = None
if isinstance(p_type, CallableType):
definition = p_type.definition
elif isinstance(p_type, Overloaded):
# Randomly select first item, if items are different, there will
# be an error during semantic analysis.
definition = p_type.items[0].definition
if definition:
if is_node_static(definition):
var.is_staticmethod = True
elif is_classmethod_node(definition):
var.is_classmethod = True
elif is_property(definition):
var.is_property = True
if isinstance(p_type, Overloaded):
# TODO: in theory we can have a property with a deleter only.
var.is_settable_property = True
assert isinstance(definition, Decorator), definition
var.setter_type = definition.var.setter_type
def set_inference_error_fallback_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:
"""Store best known type for variable if type inference failed.
If a program ignores error on type inference error, the variable should get some
inferred type so that it can used later on in the program. Example:
x = [] # type: ignore
x.append(1) # Should be ok!
We implement this here by giving x a valid type (replacing inferred Never with Any).
"""
fallback = self.inference_error_fallback_type(type)
self.set_inferred_type(var, lvalue, fallback)
def inference_error_fallback_type(self, type: Type) -> Type:
fallback = type.accept(SetNothingToAny())
# Type variables may leak from inference, see https://github.com/python/mypy/issues/5738,
# we therefore need to erase them.
return erase_typevars(fallback)
def simple_rvalue(self, rvalue: Expression) -> bool:
"""Returns True for expressions for which inferred type should not depend on context.
Note that this function can still return False for some expressions where inferred type
does not depend on context. It only exists for performance optimizations.
"""
if isinstance(rvalue, (IntExpr, StrExpr, BytesExpr, FloatExpr, RefExpr)):
return True
if isinstance(rvalue, CallExpr):
if isinstance(rvalue.callee, RefExpr) and isinstance(
rvalue.callee.node, SYMBOL_FUNCBASE_TYPES
):
typ = rvalue.callee.node.type
if isinstance(typ, CallableType):
return not typ.variables
elif isinstance(typ, Overloaded):
return not any(item.variables for item in typ.items)
return False
def check_simple_assignment(
self,
lvalue_type: Type | None,
rvalue: Expression,
context: Context,
msg: ErrorMessage = message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,
lvalue_name: str = "variable",
rvalue_name: str = "expression",
*,
notes: list[str] | None = None,
lvalue: Expression | None = None,
inferred: Var | None = None,
) -> tuple[Type, Type | None]:
if self.is_stub and isinstance(rvalue, EllipsisExpr):
# '...' is always a valid initializer in a stub.
return AnyType(TypeOfAny.special_form), lvalue_type
else:
always_allow_any = lvalue_type is not None and not isinstance(
get_proper_type(lvalue_type), AnyType
)
if inferred is None or is_typeddict_type_context(lvalue_type):
type_context = lvalue_type
else:
type_context = None
rvalue_type = self.expr_checker.accept(
rvalue, type_context=type_context, always_allow_any=always_allow_any
)
if (
lvalue_type is not None
and type_context is None
and not is_valid_inferred_type(rvalue_type, self.options)
):
# Inference in an empty type context didn't produce a valid type, so
# try using lvalue type as context instead.
rvalue_type = self.expr_checker.accept(
rvalue, type_context=lvalue_type, always_allow_any=always_allow_any
)
if not is_valid_inferred_type(rvalue_type, self.options) and inferred is not None:
self.msg.need_annotation_for_var(inferred, context, self.options)
rvalue_type = rvalue_type.accept(SetNothingToAny())
if (
isinstance(lvalue, NameExpr)
and inferred is not None
and inferred.type is not None
and not inferred.is_final
):
new_inferred = remove_instance_last_known_values(rvalue_type)
if not is_same_type(inferred.type, new_inferred):
# Should we widen the inferred type or the lvalue? Variables defined
# at module level or class bodies can't be widened in functions, or
# in another module.
if not self.refers_to_different_scope(lvalue):
lvalue_type = make_simplified_union([inferred.type, new_inferred])
if not is_same_type(lvalue_type, inferred.type) and not isinstance(
inferred.type, PartialType
):
# Widen the type to the union of original and new type.
self.widened_vars.append(inferred.name)
self.set_inferred_type(inferred, lvalue, lvalue_type)
self.binder.put(lvalue, rvalue_type)
# TODO: A bit hacky, maybe add a binder method that does put and
# updates declaration?
lit = literal_hash(lvalue)
if lit is not None:
self.binder.declarations[lit] = lvalue_type
if (
isinstance(get_proper_type(lvalue_type), UnionType)
# Skip literal types, as they have special logic (for better errors).
and not is_literal_type_like(rvalue_type)
and not self.simple_rvalue(rvalue)
):
# Try re-inferring r.h.s. in empty context, and use that if it
# results in a narrower type. We don't do this always because this
# may cause some perf impact, plus we want to partially preserve
# the old behavior. This helps with various practical examples, see
# e.g. testOptionalTypeNarrowedByGenericCall.
with self.msg.filter_errors() as local_errors, self.local_type_map as type_map:
alt_rvalue_type = self.expr_checker.accept(
rvalue, None, always_allow_any=always_allow_any
)
if (
not local_errors.has_new_errors()
# Skip Any type, since it is special cased in binder.
and not isinstance(get_proper_type(alt_rvalue_type), AnyType)
and is_valid_inferred_type(alt_rvalue_type, self.options)
and is_proper_subtype(alt_rvalue_type, rvalue_type)
):
rvalue_type = alt_rvalue_type
self.store_types(type_map)
if isinstance(rvalue_type, DeletedType):
self.msg.deleted_as_rvalue(rvalue_type, context)
if isinstance(lvalue_type, DeletedType):
self.msg.deleted_as_lvalue(lvalue_type, context)
elif lvalue_type:
self.check_subtype(
# Preserve original aliases for error messages when possible.
rvalue_type,
lvalue_type,
context,
msg,
f"{rvalue_name} has type",
f"{lvalue_name} has type",
notes=notes,
)
return rvalue_type, lvalue_type
def refers_to_different_scope(self, name: NameExpr) -> bool:
if name.kind == LDEF:
# TODO: Consider reference to outer function as a different scope?
return False
elif self.scope.top_level_function() is not None:
# A non-local reference from within a function must refer to a different scope
return True
elif name.kind == GDEF and name.fullname.rpartition(".")[0] != self.tree.fullname:
# Reference to global definition from another module
return True
return False
def check_member_assignment(
self,
lvalue: MemberExpr,
instance_type: Type,
set_lvalue_type: Type,
rvalue: Expression,
context: Context,
) -> tuple[Type, Type, bool]:
"""Type member assignment.
This defers to check_simple_assignment, unless the member expression
is a descriptor, in which case this checks descriptor semantics as well.
Return the inferred rvalue_type, inferred lvalue_type, and whether to use the binder
for this assignment.
"""
instance_type = get_proper_type(instance_type)
# Descriptors don't participate in class-attribute access
if (isinstance(instance_type, FunctionLike) and instance_type.is_type_obj()) or isinstance(
instance_type, TypeType
):
rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context)
return rvalue_type, set_lvalue_type, True
with self.msg.filter_errors(filter_deprecated=True):
get_lvalue_type = self.expr_checker.analyze_ordinary_member_access(
lvalue, is_lvalue=False
)
# Special case: if the rvalue_type is a subtype of '__get__' type, and
# '__get__' type is narrower than '__set__', then we invoke the binder to narrow type
# by this assignment. Technically, this is not safe, but in practice this is
# what a user expects.
rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context)
rvalue_type = rvalue_type if is_subtype(rvalue_type, get_lvalue_type) else get_lvalue_type
return rvalue_type, set_lvalue_type, is_subtype(get_lvalue_type, set_lvalue_type)
def check_indexed_assignment(
self, lvalue: IndexExpr, rvalue: Expression, context: Context
) -> None:
"""Type check indexed assignment base[index] = rvalue.
The lvalue argument is the base[index] expression.
"""
self.try_infer_partial_type_from_indexed_assignment(lvalue, rvalue)
basetype = get_proper_type(self.expr_checker.accept(lvalue.base))
method_type = self.expr_checker.analyze_external_member_access(
"__setitem__", basetype, lvalue
)
lvalue.method_type = method_type
res_type, _ = self.expr_checker.check_method_call(
"__setitem__",
basetype,
method_type,
[lvalue.index, rvalue],
[nodes.ARG_POS, nodes.ARG_POS],
context,
)
res_type = get_proper_type(res_type)
if isinstance(res_type, UninhabitedType) and not res_type.ambiguous:
self.binder.unreachable()
def replace_partial_type(
self, var: Var, new_type: Type, partial_types: dict[Var, Context]
) -> None:
"""Replace the partial type of var with a non-partial type."""
var.type = new_type
# Updating a partial type should invalidate expression caches.
self.binder.version += 1
del partial_types[var]
if self.options.allow_redefinition_new:
# When using --allow-redefinition-new, binder tracks all types of
# simple variables.
n = NameExpr(var.name)
n.node = var
self.binder.assign_type(n, new_type, new_type)
def try_infer_partial_type_from_indexed_assignment(
self, lvalue: IndexExpr, rvalue: Expression
) -> None:
# TODO: Should we share some of this with try_infer_partial_type?
var = None
if isinstance(lvalue.base, RefExpr) and isinstance(lvalue.base.node, Var):
var = lvalue.base.node
elif isinstance(lvalue.base, MemberExpr):
var = self.expr_checker.get_partial_self_var(lvalue.base)
if isinstance(var, Var):
if isinstance(var.type, PartialType):
type_type = var.type.type
if type_type is None:
return # The partial type is None.
partial_types = self.find_partial_types(var)
if partial_types is None:
return
typename = type_type.fullname
if (
typename == "builtins.dict"
or typename == "collections.OrderedDict"
or typename == "collections.defaultdict"
):
# TODO: Don't infer things twice.
key_type = self.expr_checker.accept(lvalue.index)
value_type = self.expr_checker.accept(rvalue)
if (
is_valid_inferred_type(key_type, self.options)
and is_valid_inferred_type(value_type, self.options)
and not self.current_node_deferred
and not (
typename == "collections.defaultdict"
and var.type.value_type is not None
and not is_equivalent(value_type, var.type.value_type)
)
):
new_type = self.named_generic_type(typename, [key_type, value_type])
self.replace_partial_type(var, new_type, partial_types)
def type_requires_usage(self, typ: Type) -> tuple[str, ErrorCode] | None:
"""Some types require usage in all cases. The classic example is
an unused coroutine.
In the case that it does require usage, returns a note to attach
to the error message.
"""
proper_type = get_proper_type(typ)
if isinstance(proper_type, Instance):
# We use different error codes for generic awaitable vs coroutine.
# Coroutines are on by default, whereas generic awaitables are not.
if proper_type.type.fullname == "typing.Coroutine":
return ("Are you missing an await?", UNUSED_COROUTINE)
if proper_type.type.get("__await__") is not None:
return ("Are you missing an await?", UNUSED_AWAITABLE)
return None
def visit_expression_stmt(self, s: ExpressionStmt) -> None:
expr_type = self.expr_checker.accept(s.expr, allow_none_return=True, always_allow_any=True)
error_note_and_code = self.type_requires_usage(expr_type)
if error_note_and_code:
error_note, code = error_note_and_code
self.fail(
message_registry.TYPE_MUST_BE_USED.format(format_type(expr_type, self.options)),
s,
code=code,
)
self.note(error_note, s, code=code)
def visit_return_stmt(self, s: ReturnStmt) -> None:
"""Type check a return statement."""
self.check_return_stmt(s)
self.binder.unreachable()
def infer_context_dependent(
self, expr: Expression, type_ctx: Type, allow_none_func_call: bool
) -> ProperType:
"""Infer type of an expression with fallback to empty type context."""
with self.msg.filter_errors(
filter_errors=True, filter_deprecated=True, save_filtered_errors=True
) as msg:
with self.local_type_map as type_map:
typ = get_proper_type(
self.expr_checker.accept(
expr, type_ctx, allow_none_return=allow_none_func_call
)
)
if not msg.has_new_errors():
self.store_types(type_map)
return typ
# If there are errors with the original type context, try re-inferring in empty context.
original_messages = msg.filtered_errors()
original_type_map = type_map
with self.msg.filter_errors(
filter_errors=True, filter_deprecated=True, save_filtered_errors=True
) as msg:
with self.local_type_map as type_map:
alt_typ = get_proper_type(
self.expr_checker.accept(expr, None, allow_none_return=allow_none_func_call)
)
if not msg.has_new_errors() and is_subtype(alt_typ, type_ctx):
self.store_types(type_map)
return alt_typ
# If empty fallback didn't work, use results from the original type context.
self.msg.add_errors(original_messages)
self.store_types(original_type_map)
return typ
def check_return_stmt(self, s: ReturnStmt) -> None:
defn = self.scope.current_function()
if defn is not None:
if defn.is_generator:
return_type = self.get_generator_return_type(
self.return_types[-1], defn.is_coroutine
)
elif defn.is_coroutine:
return_type = self.get_coroutine_return_type(self.return_types[-1])
else:
return_type = self.return_types[-1]
return_type = get_proper_type(return_type)
is_lambda = isinstance(defn, LambdaExpr)
if isinstance(return_type, UninhabitedType):
# Avoid extra error messages for failed inference in lambdas
if not is_lambda and not return_type.ambiguous:
self.fail(message_registry.NO_RETURN_EXPECTED, s)
return
if s.expr:
declared_none_return = isinstance(return_type, NoneType)
declared_any_return = isinstance(return_type, AnyType)
# This controls whether or not we allow a function call that
# returns None as the expression of this return statement.
# E.g. `return f()` for some `f` that returns None. We allow
# this only if we're in a lambda or in a function that returns
# `None` or `Any`.
allow_none_func_call = is_lambda or declared_none_return or declared_any_return
# Return with a value.
if (
isinstance(s.expr, (CallExpr, ListExpr, TupleExpr, DictExpr, SetExpr, OpExpr))
or isinstance(s.expr, AwaitExpr)
and isinstance(s.expr.expr, CallExpr)
):
# For expressions that (strongly) depend on type context (i.e. those that
# are handled like a function call), we allow fallback to empty type context
# in case of errors, this improves user experience in some cases,
# see e.g. testReturnFallbackInference.
typ = self.infer_context_dependent(s.expr, return_type, allow_none_func_call)
else:
typ = get_proper_type(
self.expr_checker.accept(
s.expr, return_type, allow_none_return=allow_none_func_call
)
)
# Treat NotImplemented as having type Any, consistent with its
# definition in typeshed prior to python/typeshed#4222.
if isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES:
typ = AnyType(TypeOfAny.special_form)
if defn.is_async_generator:
self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s)
return
# Returning a value of type Any is always fine.
if isinstance(typ, AnyType):
# (Unless you asked to be warned in that case, and the
# function is not declared to return Any)
if (
self.options.warn_return_any
and not self.current_node_deferred
and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)
and not (
defn.name in BINARY_MAGIC_METHODS
and is_literal_not_implemented(s.expr)
)
and not (
isinstance(return_type, Instance)
and return_type.type.fullname == "builtins.object"
)
and not is_lambda
):
self.msg.incorrectly_returning_any(return_type, s)
return
# Disallow return expressions in functions declared to return
# None, subject to two exceptions below.
if declared_none_return:
# Lambdas are allowed to have None returns.
# Functions returning a value of type None are allowed to have a None return.
if is_lambda or isinstance(typ, NoneType):
return
self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s)
else:
self.check_subtype(
subtype_label="got",
subtype=typ,
supertype_label="expected",
supertype=return_type,
context=s.expr,
outer_context=s,
msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE,
)
else:
# Empty returns are valid in Generators with Any typed returns, but not in
# coroutines.
if (
defn.is_generator
and not defn.is_coroutine
and isinstance(return_type, AnyType)
):
return
if isinstance(return_type, (NoneType, AnyType)):
return
if self.in_checked_function():
self.fail(message_registry.RETURN_VALUE_EXPECTED, s)
def visit_if_stmt(self, s: IfStmt) -> None:
"""Type check an if statement."""
# This frame records the knowledge from previous if/elif clauses not being taken.
# Fall-through to the original frame is handled explicitly in each block.
with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=0):
for e, b in zip(s.expr, s.body):
t = get_proper_type(self.expr_checker.accept(e))
if isinstance(t, DeletedType):
self.msg.deleted_as_rvalue(t, s)
if_map, else_map = self.find_isinstance_check(e)
# XXX Issue a warning if condition is always False?
with self.binder.frame_context(can_skip=True, fall_through=2):
self.push_type_map(if_map, from_assignment=False)
self.accept(b)
# XXX Issue a warning if condition is always True?
self.push_type_map(else_map, from_assignment=False)
with self.binder.frame_context(can_skip=False, fall_through=2):
if s.else_body:
self.accept(s.else_body)
def visit_while_stmt(self, s: WhileStmt) -> None:
"""Type check a while statement."""
if_stmt = IfStmt([s.expr], [s.body], None)
if_stmt.set_line(s)
self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr)
def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None:
"""Type check an operator assignment statement, e.g. x += 1."""
self.try_infer_partial_generic_type_from_assignment(s.lvalue, s.rvalue, s.op)
if isinstance(s.lvalue, MemberExpr):
# Special case, some additional errors may be given for
# assignments to read-only or final attributes.
lvalue_type = self.expr_checker.visit_member_expr(s.lvalue, True)
else:
lvalue_type = self.expr_checker.accept(s.lvalue)
inplace, method = infer_operator_assignment_method(lvalue_type, s.op)
if inplace:
# There is __ifoo__, treat as x = x.__ifoo__(y)
rvalue_type, _ = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s)
if not is_subtype(rvalue_type, lvalue_type):
self.msg.incompatible_operator_assignment(s.op, s)
else:
# There is no __ifoo__, treat as x = x <foo> y
expr = OpExpr(s.op, s.lvalue, s.rvalue)
expr.set_line(s)
self.check_assignment(
lvalue=s.lvalue, rvalue=expr, infer_lvalue_type=True, new_syntax=False
)
self.check_final(s)
def visit_assert_stmt(self, s: AssertStmt) -> None:
self.expr_checker.accept(s.expr)
if isinstance(s.expr, TupleExpr) and len(s.expr.items) > 0:
self.fail(message_registry.MALFORMED_ASSERT, s)
# If this is asserting some isinstance check, bind that type in the following code
true_map, else_map = self.find_isinstance_check(s.expr)
if s.msg is not None:
self.expr_checker.analyze_cond_branch(
else_map, s.msg, None, suppress_unreachable_errors=False
)
self.push_type_map(true_map)
def visit_raise_stmt(self, s: RaiseStmt) -> None:
"""Type check a raise statement."""
if s.expr:
self.type_check_raise(s.expr, s)
if s.from_expr:
self.type_check_raise(s.from_expr, s, optional=True)
self.binder.unreachable()
def type_check_raise(self, e: Expression, s: RaiseStmt, optional: bool = False) -> None:
typ = get_proper_type(self.expr_checker.accept(e))
if isinstance(typ, DeletedType):
self.msg.deleted_as_rvalue(typ, e)
return
exc_type = self.named_type("builtins.BaseException")
expected_type_items = [exc_type, TypeType(exc_type)]
if optional:
# This is used for `x` part in a case like `raise e from x`,
# where we allow `raise e from None`.
expected_type_items.append(NoneType())
self.check_subtype(
typ, UnionType.make_union(expected_type_items), s, message_registry.INVALID_EXCEPTION
)
if isinstance(typ, FunctionLike):
# https://github.com/python/mypy/issues/11089
self.expr_checker.check_call(typ, [], [], e)
if (isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES) or (
isinstance(e, CallExpr)
and isinstance(e.callee, RefExpr)
and e.callee.fullname == "builtins.NotImplemented"
):
self.fail(
message_registry.INVALID_EXCEPTION.with_additional_msg(
'; did you mean "NotImplementedError"?'
),
s,
)
def visit_try_stmt(self, s: TryStmt) -> None:
"""Type check a try statement."""
iter_errors = None
# Our enclosing frame will get the result if the try/except falls through.
# This one gets all possible states after the try block exited abnormally
# (by exception, return, break, etc.)
with self.binder.frame_context(can_skip=False, fall_through=0):
# Not only might the body of the try statement exit
# abnormally, but so might an exception handler or else
# clause. The finally clause runs in *all* cases, so we
# need an outer try frame to catch all intermediate states
# in case an exception is raised during an except or else
# clause. As an optimization, only create the outer try
# frame when there actually is a finally clause.
self.visit_try_without_finally(s, try_frame=bool(s.finally_body))
if s.finally_body:
# First we check finally_body is type safe on all abnormal exit paths
iter_errors = IterationDependentErrors()
with IterationErrorWatcher(self.msg.errors, iter_errors):
self.accept(s.finally_body)
if s.finally_body:
# Then we try again for the more restricted set of options
# that can fall through. (Why do we need to check the
# finally clause twice? Depending on whether the finally
# clause was reached by the try clause falling off the end
# or exiting abnormally, after completing the finally clause
# either flow will continue to after the entire try statement
# or the exception/return/etc. will be processed and control
# flow will escape. We need to check that the finally clause
# type checks in both contexts, but only the resulting types
# from the latter context affect the type state in the code
# that follows the try statement.)
assert iter_errors is not None
if not self.binder.is_unreachable():
with IterationErrorWatcher(self.msg.errors, iter_errors):
self.accept(s.finally_body)
self.msg.iteration_dependent_errors(iter_errors)
def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:
"""Type check a try statement, ignoring the finally block.
On entry, the top frame should receive all flow that exits the
try block abnormally (i.e., such that the else block does not
execute), and its parent should receive all flow that exits
the try block normally.
"""
# This frame will run the else block if the try fell through.
# In that case, control flow continues to the parent of what
# was the top frame on entry.
with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=try_frame):
# This frame receives exit via exception, and runs exception handlers
with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=2):
# Finally, the body of the try statement
with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=True):
self.accept(s.body)
for i in range(len(s.handlers)):
with self.binder.frame_context(can_skip=True, fall_through=4):
typ = s.types[i]
if typ:
t = self.check_except_handler_test(typ, s.is_star)
var = s.vars[i]
if var:
# To support local variables, we make this a definition line,
# causing assignment to set the variable's type.
var.is_inferred_def = True
self.check_assignment(var, self.temp_node(t, var))
self.accept(s.handlers[i])
var = s.vars[i]
if var:
# Exception variables are deleted.
# Unfortunately, this doesn't let us detect usage before the
# try/except block.
source = var.name
if isinstance(var.node, Var):
new_type = DeletedType(source=source)
var.node.type = new_type
if self.options.allow_redefinition_new:
# TODO: Should we use put() here?
self.binder.assign_type(var, new_type, new_type)
if not self.options.allow_redefinition_new:
self.binder.cleanse(var)
if s.else_body:
self.accept(s.else_body)
def check_except_handler_test(self, n: Expression, is_star: bool) -> Type:
"""Type check an exception handler test clause."""
typ = self.expr_checker.accept(n)
all_types: list[Type] = []
test_types = self.get_types_from_except_handler(typ, n)
for ttype in get_proper_types(test_types):
if isinstance(ttype, AnyType):
all_types.append(ttype)
continue
if isinstance(ttype, FunctionLike):
item = ttype.items[0]
if not item.is_type_obj():
self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
return self.default_exception_type(is_star)
exc_type = erase_typevars(item.ret_type)
elif isinstance(ttype, TypeType):
exc_type = ttype.item
else:
self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
return self.default_exception_type(is_star)
if not is_subtype(exc_type, self.named_type("builtins.BaseException")):
self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
return self.default_exception_type(is_star)
all_types.append(exc_type)
if is_star:
new_all_types: list[Type] = []
for typ in all_types:
if is_proper_subtype(typ, self.named_type("builtins.BaseExceptionGroup")):
self.fail(message_registry.INVALID_EXCEPTION_GROUP, n)
new_all_types.append(AnyType(TypeOfAny.from_error))
else:
new_all_types.append(typ)
return self.wrap_exception_group(new_all_types)
return make_simplified_union(all_types)
def default_exception_type(self, is_star: bool) -> Type:
"""Exception type to return in case of a previous type error."""
any_type = AnyType(TypeOfAny.from_error)
if is_star:
return self.named_generic_type("builtins.ExceptionGroup", [any_type])
return any_type
def wrap_exception_group(self, types: Sequence[Type]) -> Type:
"""Transform except* variable type into an appropriate exception group."""
arg = make_simplified_union(types)
if is_subtype(arg, self.named_type("builtins.Exception")):
base = "builtins.ExceptionGroup"
else:
base = "builtins.BaseExceptionGroup"
return self.named_generic_type(base, [arg])
def get_types_from_except_handler(self, typ: Type, n: Expression) -> list[Type]:
"""Helper for check_except_handler_test to retrieve handler types."""
typ = get_proper_type(typ)
if isinstance(typ, TupleType):
merged_type = make_simplified_union(typ.items)
if isinstance(merged_type, UnionType):
return merged_type.relevant_items()
return [merged_type]
elif is_named_instance(typ, "builtins.tuple"):
# variadic tuple
merged_type = make_simplified_union((typ.args[0],))
if isinstance(merged_type, UnionType):
return merged_type.relevant_items()
return [merged_type]
elif isinstance(typ, UnionType):
return [
union_typ
for item in typ.relevant_items()
for union_typ in self.get_types_from_except_handler(item, n)
]
else:
return [typ]
def visit_for_stmt(self, s: ForStmt) -> None:
"""Type check a for statement."""
if s.is_async:
iterator_type, item_type = self.analyze_async_iterable_item_type(s.expr)
else:
iterator_type, item_type = self.analyze_iterable_item_type(s.expr)
s.inferred_item_type = item_type
s.inferred_iterator_type = iterator_type
self.accept_loop(
s.body,
s.else_body,
on_enter_body=lambda: self.analyze_index_variables(
s.index, item_type, s.index_type is None, s
),
)
def analyze_async_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:
"""Analyse async iterable expression and return iterator and iterator item types."""
echk = self.expr_checker
iterable = echk.accept(expr)
iterator = echk.check_method_call_by_name("__aiter__", iterable, [], [], expr)[0]
awaitable = echk.check_method_call_by_name("__anext__", iterator, [], [], expr)[0]
item_type = echk.check_awaitable_expr(
awaitable, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_FOR
)
return iterator, item_type
def analyze_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:
"""Analyse iterable expression and return iterator and iterator item types."""
iterator, iterable = self.analyze_iterable_item_type_without_expression(
self.expr_checker.accept(expr), context=expr
)
int_type = self.analyze_range_native_int_type(expr)
if int_type:
return iterator, int_type
return iterator, iterable
def analyze_iterable_item_type_without_expression(
self, type: Type, context: Context
) -> tuple[Type, Type]:
"""Analyse iterable type and return iterator and iterator item types."""
echk = self.expr_checker
iterable: Type
iterable = get_proper_type(type)
iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], context)[0]
if (
isinstance(iterable, TupleType)
and iterable.partial_fallback.type.fullname == "builtins.tuple"
):
return iterator, tuple_fallback(iterable).args[0]
else:
# Non-tuple iterable.
iterable = echk.check_method_call_by_name("__next__", iterator, [], [], context)[0]
return iterator, iterable
def analyze_range_native_int_type(self, expr: Expression) -> Type | None:
"""Try to infer native int item type from arguments to range(...).
For example, return i64 if the expression is "range(0, i64(n))".
Return None if unsuccessful.
"""
if (
isinstance(expr, CallExpr)
and isinstance(expr.callee, RefExpr)
and expr.callee.fullname == "builtins.range"
and 1 <= len(expr.args) <= 3
and all(kind == ARG_POS for kind in expr.arg_kinds)
):
native_int: Type | None = None
ok = True
for arg in expr.args:
argt = get_proper_type(self.lookup_type(arg))
if isinstance(argt, Instance) and argt.type.fullname in MYPYC_NATIVE_INT_NAMES:
if native_int is None:
native_int = argt
elif argt != native_int:
ok = False
if ok and native_int:
return native_int
return None
def analyze_container_item_type(self, typ: Type) -> Type | None:
"""Check if a type is a nominal container of a union of such.
Return the corresponding container item type.
"""
typ = get_proper_type(typ)
if isinstance(typ, UnionType):
types: list[Type] = []
for item in typ.items:
c_type = self.analyze_container_item_type(item)
if c_type:
types.append(c_type)
return UnionType.make_union(types)
if isinstance(typ, Instance) and typ.type.has_base("typing.Container"):
supertype = self.named_type("typing.Container").type
super_instance = map_instance_to_supertype(typ, supertype)
assert len(super_instance.args) == 1
return super_instance.args[0]
if isinstance(typ, TupleType):
return self.analyze_container_item_type(tuple_fallback(typ))
return None
def analyze_index_variables(
self, index: Expression, item_type: Type, infer_lvalue_type: bool, context: Context
) -> None:
"""Type check or infer for loop or list comprehension index vars."""
self.check_assignment(index, self.temp_node(item_type, context), infer_lvalue_type)
def visit_del_stmt(self, s: DelStmt) -> None:
if isinstance(s.expr, IndexExpr):
e = s.expr
m = MemberExpr(e.base, "__delitem__")
m.line = s.line
m.column = s.column
c = CallExpr(m, [e.index], [nodes.ARG_POS], [None])
c.line = s.line
c.column = s.column
self.expr_checker.accept(c, allow_none_return=True)
else:
s.expr.accept(self.expr_checker)
for elt in flatten(s.expr):
if isinstance(elt, NameExpr):
self.binder.assign_type(
elt, DeletedType(source=elt.name), get_declaration(elt)
)
def visit_decorator(self, e: Decorator) -> None:
for d in e.decorators:
if isinstance(d, RefExpr):
if d.fullname == "typing.no_type_check":
e.var.type = AnyType(TypeOfAny.special_form)
e.var.is_ready = True
return
self.visit_decorator_inner(e)
def visit_decorator_inner(
self, e: Decorator, allow_empty: bool = False, skip_first_item: bool = False
) -> None:
if self.recurse_into_functions:
with self.tscope.function_scope(e.func):
self.check_func_item(e.func, name=e.func.name, allow_empty=allow_empty)
# Process decorators from the inside out to determine decorated signature, which
# may be different from the declared signature.
sig: Type = self.function_type(e.func)
non_trivial_decorator = False
# For settable properties skip the first decorator (that is @foo.setter).
for d in reversed(e.decorators[1:] if skip_first_item else e.decorators):
if refers_to_fullname(d, "abc.abstractmethod"):
# This is a hack to avoid spurious errors because of incomplete type
# of @abstractmethod in the test fixtures.
continue
if refers_to_fullname(d, OVERLOAD_NAMES):
if not allow_empty:
self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, e)
continue
non_trivial_decorator = True
dec = self.expr_checker.accept(d)
temp = self.temp_node(sig, context=d)
fullname = None
if isinstance(d, RefExpr):
fullname = d.fullname or None
# if this is an expression like @b.a where b is an object, get the type of b,
# so we can pass it the method hook in the plugins
object_type: Type | None = None
if fullname is None and isinstance(d, MemberExpr) and self.has_type(d.expr):
object_type = self.lookup_type(d.expr)
fullname = self.expr_checker.method_fullname(object_type, d.name)
self.check_for_untyped_decorator(e.func, dec, d)
sig, t2 = self.expr_checker.check_call(
dec, [temp], [nodes.ARG_POS], e, callable_name=fullname, object_type=object_type
)
if non_trivial_decorator:
self.check_untyped_after_decorator(sig, e.func)
self.require_correct_self_argument(sig, e.func)
sig = set_callable_name(sig, e.func)
if isinstance(sig, CallableType):
sig.definition = e
e.var.type = sig
e.var.is_ready = True
if e.func.is_property:
if isinstance(sig, CallableType):
if len([k for k in sig.arg_kinds if k.is_required()]) > 1:
self.msg.fail("Too many arguments for property", e)
self.check_incompatible_property_override(e)
# For overloaded functions/properties we already checked override for overload as a whole.
if allow_empty or skip_first_item:
return
if e.func.info and not e.is_overload:
found_method_base_classes = self.check_method_override(e)
if (
e.func.is_explicit_override
and not found_method_base_classes
and found_method_base_classes is not None
# If the class has Any fallback, we can't be certain that a method
# is really missing - it might come from unfollowed import.
and not e.func.info.fallback_to_any
):
self.msg.no_overridable_method(e.func.name, e.func)
self.check_explicit_override_decorator(e.func, found_method_base_classes)
if e.func.info and e.func.name in ("__init__", "__new__"):
if e.type and not isinstance(get_proper_type(e.type), (FunctionLike, AnyType)):
self.fail(message_registry.BAD_CONSTRUCTOR_TYPE, e)
if e.func.original_def and isinstance(sig, FunctionLike):
# Function definition overrides function definition.
self.check_func_def_override(e.func, sig)
def check_for_untyped_decorator(
self, func: FuncDef, dec_type: Type, dec_expr: Expression
) -> None:
if (
self.options.disallow_untyped_decorators
and is_typed_callable(func.type)
and is_untyped_decorator(dec_type)
and not self.current_node_deferred
):
self.msg.typed_function_untyped_decorator(func.name, dec_expr)
def check_incompatible_property_override(self, e: Decorator) -> None:
if not e.var.is_settable_property and e.func.info:
name = e.func.name
for base in e.func.info.mro[1:]:
base_attr = base.names.get(name)
if not base_attr:
continue
if (
isinstance(base_attr.node, OverloadedFuncDef)
and base_attr.node.is_property
and cast(Decorator, base_attr.node.items[0]).var.is_settable_property
):
self.fail(message_registry.READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE, e)
def visit_with_stmt(self, s: WithStmt) -> None:
exceptions_maybe_suppressed = False
for expr, target in zip(s.expr, s.target):
if s.is_async:
exit_ret_type = self.check_async_with_item(expr, target, s.unanalyzed_type is None)
else:
exit_ret_type = self.check_with_item(expr, target, s.unanalyzed_type is None)
# Based on the return type, determine if this context manager 'swallows'
# exceptions or not. We determine this using a heuristic based on the
# return type of the __exit__ method -- see the discussion in
# https://github.com/python/mypy/issues/7214 and the section about context managers
# in https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions
# for more details.
exit_ret_type = get_proper_type(exit_ret_type)
if is_literal_type(exit_ret_type, "builtins.bool", False):
continue
if is_literal_type(exit_ret_type, "builtins.bool", True) or (
isinstance(exit_ret_type, Instance)
and exit_ret_type.type.fullname == "builtins.bool"
and state.strict_optional
):
# Note: if strict-optional is disabled, this bool instance
# could actually be an Optional[bool].
exceptions_maybe_suppressed = True
if exceptions_maybe_suppressed:
# Treat this 'with' block in the same way we'd treat a 'try: BODY; except: pass'
# block. This means control flow can continue after the 'with' even if the 'with'
# block immediately returns.
with self.binder.frame_context(can_skip=True, try_frame=True):
self.accept(s.body)
else:
self.accept(s.body)
def check_untyped_after_decorator(self, typ: Type, func: FuncDef) -> None:
if not self.options.disallow_any_decorated or self.is_stub or self.current_node_deferred:
return
if mypy.checkexpr.has_any_type(typ):
self.msg.untyped_decorated_function(typ, func)
def check_async_with_item(
self, expr: Expression, target: Expression | None, infer_lvalue_type: bool
) -> Type:
echk = self.expr_checker
ctx = echk.accept(expr)
obj = echk.check_method_call_by_name("__aenter__", ctx, [], [], expr)[0]
obj = echk.check_awaitable_expr(
obj, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER
)
if target:
self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)
arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)
res, _ = echk.check_method_call_by_name(
"__aexit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr
)
return echk.check_awaitable_expr(
res, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT
)
def check_with_item(
self, expr: Expression, target: Expression | None, infer_lvalue_type: bool
) -> Type:
echk = self.expr_checker
ctx = echk.accept(expr)
obj = echk.check_method_call_by_name("__enter__", ctx, [], [], expr)[0]
if target:
self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)
arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)
res, _ = echk.check_method_call_by_name(
"__exit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr
)
return res
def visit_break_stmt(self, s: BreakStmt) -> None:
self.binder.handle_break()
def visit_continue_stmt(self, s: ContinueStmt) -> None:
self.binder.handle_continue()
return
def visit_match_stmt(self, s: MatchStmt) -> None:
# In sync with similar actions elsewhere, narrow the target if
# we are matching an AssignmentExpr
unwrapped_subject = collapse_walrus(s.subject)
named_subject = self._make_named_statement_for_match(s, unwrapped_subject)
with self.binder.frame_context(can_skip=False, fall_through=0):
subject_type = get_proper_type(self.expr_checker.accept(s.subject))
if isinstance(subject_type, DeletedType):
self.msg.deleted_as_rvalue(subject_type, s)
# We infer types of patterns twice. The first pass is used
# to infer the types of capture variables. The type of a
# capture variable may depend on multiple patterns (it
# will be a union of all capture types). This pass ignores
# guard expressions.
pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]
type_maps: list[TypeMap] = [t.captures for t in pattern_types]
inferred_types = self.infer_variable_types_from_type_maps(type_maps)
# The second pass narrows down the types and type checks bodies.
unmatched_types: TypeMap = None
for p, g, b in zip(s.patterns, s.guards, s.bodies):
current_subject_type = self.expr_checker.narrow_type_from_binder(
named_subject, subject_type
)
pattern_type = self.pattern_checker.accept(p, current_subject_type)
with self.binder.frame_context(can_skip=True, fall_through=2):
if b.is_unreachable or isinstance(
get_proper_type(pattern_type.type), UninhabitedType
):
self.push_type_map(None, from_assignment=False)
else_map: TypeMap = {}
else:
pattern_map, else_map = conditional_types_to_typemaps(
named_subject, pattern_type.type, pattern_type.rest_type
)
# Maybe the subject type can be inferred from constraints on
# its attribute/item?
if pattern_map and named_subject in pattern_map:
pattern_map[unwrapped_subject] = pattern_map[named_subject]
if else_map and named_subject in else_map:
else_map[unwrapped_subject] = else_map[named_subject]
pattern_map = self.propagate_up_typemap_info(pattern_map)
else_map = self.propagate_up_typemap_info(else_map)
self.remove_capture_conflicts(pattern_type.captures, inferred_types)
self.push_type_map(pattern_map, from_assignment=False)
if pattern_map:
for expr, typ in pattern_map.items():
self.push_type_map(
self._get_recursive_sub_patterns_map(expr, typ),
from_assignment=False,
)
self.push_type_map(pattern_type.captures, from_assignment=False)
if g is not None:
with self.binder.frame_context(can_skip=False, fall_through=3):
gt = get_proper_type(self.expr_checker.accept(g))
if isinstance(gt, DeletedType):
self.msg.deleted_as_rvalue(gt, s)
guard_map, guard_else_map = self.find_isinstance_check(g)
else_map = or_conditional_maps(else_map, guard_else_map)
# If the guard narrowed the subject, copy the narrowed types over
if isinstance(p, AsPattern):
case_target = p.pattern or p.name
if isinstance(case_target, NameExpr):
for type_map in (guard_map, else_map):
if not type_map:
continue
for expr in list(type_map):
if not (
isinstance(expr, NameExpr)
and expr.fullname == case_target.fullname
):
continue
type_map[named_subject] = type_map[expr]
self.push_type_map(guard_map, from_assignment=False)
self.accept(b)
else:
self.accept(b)
self.push_type_map(else_map, from_assignment=False)
unmatched_types = else_map
if unmatched_types is not None and not self.current_node_deferred:
for typ in unmatched_types.values():
self.msg.match_statement_inexhaustive_match(typ, s)
# This is needed due to a quirk in frame_context. Without it types will stay narrowed
# after the match.
with self.binder.frame_context(can_skip=False, fall_through=2):
pass
def _make_named_statement_for_match(self, s: MatchStmt, subject: Expression) -> Expression:
"""Construct a fake NameExpr for inference if a match clause is complex."""
if self.binder.can_put_directly(subject):
# Already named - we should infer type of it as given
return subject
elif s.subject_dummy is not None:
return s.subject_dummy
else:
# Create a dummy subject expression to handle cases where a match statement's subject
# is not a literal value. This lets us correctly narrow types and check exhaustivity
# This is hack!
name = self.new_unique_dummy_name("match")
v = Var(name)
named_subject = NameExpr(name)
named_subject.node = v
s.subject_dummy = named_subject
return named_subject
def _get_recursive_sub_patterns_map(
self, expr: Expression, typ: Type
) -> dict[Expression, Type]:
sub_patterns_map: dict[Expression, Type] = {}
typ_ = get_proper_type(typ)
if isinstance(expr, TupleExpr) and isinstance(typ_, TupleType):
# When matching a tuple expression with a sequence pattern, narrow individual tuple items
assert len(expr.items) == len(typ_.items)
for item_expr, item_typ in zip(expr.items, typ_.items):
sub_patterns_map[item_expr] = item_typ
sub_patterns_map.update(self._get_recursive_sub_patterns_map(item_expr, item_typ))
return sub_patterns_map
def infer_variable_types_from_type_maps(
self, type_maps: list[TypeMap]
) -> dict[SymbolNode, Type]:
# Type maps may contain variables inherited from previous code which are not
# necessary `Var`s (e.g. a function defined earlier with the same name).
all_captures: dict[SymbolNode, list[tuple[NameExpr, Type]]] = defaultdict(list)
for tm in type_maps:
if tm is not None:
for expr, typ in tm.items():
if isinstance(expr, NameExpr):
node = expr.node
assert node is not None
all_captures[node].append((expr, typ))
inferred_types: dict[SymbolNode, Type] = {}
for var, captures in all_captures.items():
already_exists = False
types: list[Type] = []
for expr, typ in captures:
types.append(typ)
previous_type, _, _ = self.check_lvalue(expr)
if previous_type is not None:
already_exists = True
if isinstance(expr.node, Var) and expr.node.is_final:
self.msg.cant_assign_to_final(expr.name, False, expr)
if self.check_subtype(
typ,
previous_type,
expr,
msg=message_registry.INCOMPATIBLE_TYPES_IN_CAPTURE,
subtype_label="pattern captures type",
supertype_label="variable has type",
):
inferred_types[var] = previous_type
if not already_exists:
new_type = UnionType.make_union(types)
# Infer the union type at the first occurrence
first_occurrence, _ = captures[0]
# If it didn't exist before ``match``, it's a Var.
assert isinstance(var, Var)
inferred_types[var] = new_type
self.infer_variable_type(var, first_occurrence, new_type, first_occurrence)
return inferred_types
def remove_capture_conflicts(
self, type_map: TypeMap, inferred_types: dict[SymbolNode, Type]
) -> None:
if type_map:
for expr, typ in list(type_map.items()):
if isinstance(expr, NameExpr):
node = expr.node
if node not in inferred_types or not is_subtype(typ, inferred_types[node]):
del type_map[expr]
def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None:
if o.alias_node:
self.check_typevar_defaults(o.alias_node.alias_tvars)
with self.msg.filter_errors():
self.expr_checker.accept(o.value)
def make_fake_typeinfo(
self,
curr_module_fullname: str,
class_gen_name: str,
class_short_name: str,
bases: list[Instance],
) -> tuple[ClassDef, TypeInfo]:
# Build the fake ClassDef and TypeInfo together.
# The ClassDef is full of lies and doesn't actually contain a body.
# Use format_bare to generate a nice name for error messages.
# We skip fully filling out a handful of TypeInfo fields because they
# should be irrelevant for a generated type like this:
# is_protocol, protocol_members, is_abstract
cdef = ClassDef(class_short_name, Block([]))
cdef.fullname = curr_module_fullname + "." + class_gen_name
info = TypeInfo(SymbolTable(), cdef, curr_module_fullname)
cdef.info = info
info.bases = bases
calculate_mro(info)
info.metaclass_type = info.calculate_metaclass_type()
return cdef, info
def intersect_instances(
self, instances: tuple[Instance, Instance], errors: list[tuple[str, str]]
) -> Instance | None:
"""Try creating an ad-hoc intersection of the given instances.
Note that this function does *not* try and create a full-fledged
intersection type. Instead, it returns an instance of a new ad-hoc
subclass of the given instances.
This is mainly useful when you need a way of representing some
theoretical subclass of the instances the user may be trying to use
the generated intersection can serve as a placeholder.
This function will create a fresh subclass the first time you call it.
So this means calling `self.intersect_intersection([inst_1, inst_2], ctx)`
twice will return the same subclass of inst_1 and inst_2.
Returns None if creating the subclass is impossible (e.g. due to
MRO errors or incompatible signatures). If we do successfully create
a subclass, its TypeInfo will automatically be added to the global scope.
"""
curr_module = self.scope.stack[0]
assert isinstance(curr_module, MypyFile)
# First, retry narrowing while allowing promotions (they are disabled by default
# for isinstance() checks, etc). This way we will still type-check branches like
# x: complex = 1
# if isinstance(x, int):
# ...
left, right = instances
if is_proper_subtype(left, right, ignore_promotions=False):
return left
if is_proper_subtype(right, left, ignore_promotions=False):
return right
def _get_base_classes(instances_: tuple[Instance, Instance]) -> list[Instance]:
base_classes_ = []
for inst in instances_:
if inst.type.is_intersection:
expanded = inst.type.bases
else:
expanded = [inst]
for expanded_inst in expanded:
base_classes_.append(expanded_inst)
return base_classes_
def _make_fake_typeinfo_and_full_name(
base_classes_: list[Instance], curr_module_: MypyFile, options: Options
) -> tuple[TypeInfo, str]:
names = [format_type_bare(x, options=options, verbosity=2) for x in base_classes_]
name = f"<subclass of {pretty_seq(names, 'and')}>"
if (symbol := curr_module_.names.get(name)) is not None:
assert isinstance(symbol.node, TypeInfo)
return symbol.node, name
cdef, info_ = self.make_fake_typeinfo(curr_module_.fullname, name, name, base_classes_)
return info_, name
base_classes = _get_base_classes(instances)
# We use the pretty_names_list for error messages but for the real name that goes
# into the symbol table because it is not specific enough.
pretty_names_list = pretty_seq(
format_type_distinctly(*base_classes, options=self.options, bare=True), "and"
)
if not can_have_shared_disjoint_base(base_classes):
errors.append((pretty_names_list, "have distinct disjoint bases"))
return None
new_errors = []
for base in base_classes:
if base.type.is_final:
new_errors.append((pretty_names_list, f'"{base.type.name}" is final'))
if new_errors:
errors.extend(new_errors)
return None
try:
info, full_name = _make_fake_typeinfo_and_full_name(
base_classes, curr_module, self.options
)
with self.msg.filter_errors() as local_errors:
self.check_multiple_inheritance(info)
if local_errors.has_new_errors():
# "class A(B, C)" unsafe, now check "class A(C, B)":
base_classes = _get_base_classes(instances[::-1])
info, full_name = _make_fake_typeinfo_and_full_name(
base_classes, curr_module, self.options
)
with self.msg.filter_errors() as local_errors:
self.check_multiple_inheritance(info)
info.is_intersection = True
except MroError:
errors.append((pretty_names_list, "would have inconsistent method resolution order"))
return None
if local_errors.has_new_errors():
errors.append((pretty_names_list, "would have incompatible method signatures"))
return None
curr_module.names[full_name] = SymbolTableNode(GDEF, info)
return Instance(info, [], extra_attrs=instances[0].extra_attrs or instances[1].extra_attrs)
def intersect_instance_callable(self, typ: Instance, callable_type: CallableType) -> Instance:
"""Creates a fake type that represents the intersection of an Instance and a CallableType.
It operates by creating a bare-minimum dummy TypeInfo that
subclasses type and adds a __call__ method matching callable_type.
"""
# In order for this to work in incremental mode, the type we generate needs to
# have a valid fullname and a corresponding entry in a symbol table. We generate
# a unique name inside the symbol table of the current module.
cur_module = self.scope.stack[0]
assert isinstance(cur_module, MypyFile)
gen_name = gen_unique_name(f"<callable subtype of {typ.type.name}>", cur_module.names)
# Synthesize a fake TypeInfo
short_name = format_type_bare(typ, self.options)
cdef, info = self.make_fake_typeinfo(cur_module.fullname, gen_name, short_name, [typ])
# Build up a fake FuncDef so we can populate the symbol table.
func_def = FuncDef("__call__", [], Block([]), callable_type)
func_def._fullname = cdef.fullname + ".__call__"
func_def.info = info
info.names["__call__"] = SymbolTableNode(MDEF, func_def)
cur_module.names[gen_name] = SymbolTableNode(GDEF, info)
return Instance(info, [], extra_attrs=typ.extra_attrs)
def make_fake_callable(self, typ: Instance) -> Instance:
"""Produce a new type that makes type Callable with a generic callable type."""
fallback = self.named_type("builtins.function")
callable_type = CallableType(
[AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)],
[nodes.ARG_STAR, nodes.ARG_STAR2],
[None, None],
ret_type=AnyType(TypeOfAny.explicit),
fallback=fallback,
is_ellipsis_args=True,
)
return self.intersect_instance_callable(typ, callable_type)
def partition_by_callable(
self, typ: Type, unsound_partition: bool
) -> tuple[list[Type], list[Type]]:
"""Partitions a type into callable subtypes and uncallable subtypes.
Thus, given:
`callables, uncallables = partition_by_callable(type)`
If we assert `callable(type)` then `type` has type Union[*callables], and
If we assert `not callable(type)` then `type` has type Union[*uncallables]
If unsound_partition is set, assume that anything that is not
clearly callable is in fact not callable. Otherwise we generate a
new subtype that *is* callable.
Guaranteed to not return [], [].
"""
typ = get_proper_type(typ)
if isinstance(typ, (FunctionLike, TypeType)):
return [typ], []
if isinstance(typ, AnyType):
return [typ], [typ]
if isinstance(typ, NoneType):
return [], [typ]
if isinstance(typ, UnionType):
callables = []
uncallables = []
for subtype in typ.items:
# Use unsound_partition when handling unions in order to
# allow the expected type discrimination.
subcallables, subuncallables = self.partition_by_callable(
subtype, unsound_partition=True
)
callables.extend(subcallables)
uncallables.extend(subuncallables)
return callables, uncallables
if isinstance(typ, TypeVarType):
# We could do better probably?
# Refine the type variable's bound as our type in the case that
# callable() is true. This unfortunately loses the information that
# the type is a type variable in that branch.
# This matches what is done for isinstance, but it may be possible to
# do better.
# If it is possible for the false branch to execute, return the original
# type to avoid losing type information.
callables, uncallables = self.partition_by_callable(
erase_to_union_or_bound(typ), unsound_partition
)
uncallables = [typ] if uncallables else []
return callables, uncallables
# A TupleType is callable if its fallback is, but needs special handling
# when we dummy up a new type.
ityp = typ
if isinstance(typ, TupleType):
ityp = tuple_fallback(typ)
if isinstance(ityp, Instance):
method = ityp.type.get_method("__call__")
if method and method.type:
callables, uncallables = self.partition_by_callable(
method.type, unsound_partition=False
)
if callables and not uncallables:
# Only consider the type callable if its __call__ method is
# definitely callable.
return [typ], []
if not unsound_partition:
fake = self.make_fake_callable(ityp)
if isinstance(typ, TupleType):
fake.type.tuple_type = TupleType(typ.items, fake)
return [fake.type.tuple_type], [typ]
return [fake], [typ]
if unsound_partition:
return [], [typ]
else:
# We don't know how properly make the type callable.
return [typ], [typ]
def conditional_callable_type_map(
self, expr: Expression, current_type: Type | None
) -> tuple[TypeMap, TypeMap]:
"""Takes in an expression and the current type of the expression.
Returns a 2-tuple: The first element is a map from the expression to
the restricted type if it were callable. The second element is a
map from the expression to the type it would hold if it weren't
callable.
"""
if not current_type:
return {}, {}
if isinstance(get_proper_type(current_type), AnyType):
return {}, {}
callables, uncallables = self.partition_by_callable(current_type, unsound_partition=False)
if callables and uncallables:
callable_map = {expr: UnionType.make_union(callables)} if callables else None
uncallable_map = {expr: UnionType.make_union(uncallables)} if uncallables else None
return callable_map, uncallable_map
elif callables:
return {}, None
return None, {}
def conditional_types_for_iterable(
self, item_type: Type, iterable_type: Type
) -> tuple[Type | None, Type | None]:
"""
Narrows the type of `iterable_type` based on the type of `item_type`.
For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s).
"""
if_types: list[Type] = []
else_types: list[Type] = []
iterable_type = get_proper_type(iterable_type)
if isinstance(iterable_type, UnionType):
possible_iterable_types = get_proper_types(iterable_type.relevant_items())
else:
possible_iterable_types = [iterable_type]
item_str_literals = try_getting_str_literals_from_type(item_type)
for possible_iterable_type in possible_iterable_types:
if item_str_literals and isinstance(possible_iterable_type, TypedDictType):
for key in item_str_literals:
if key in possible_iterable_type.required_keys:
if_types.append(possible_iterable_type)
elif (
key in possible_iterable_type.items or not possible_iterable_type.is_final
):
if_types.append(possible_iterable_type)
else_types.append(possible_iterable_type)
else:
else_types.append(possible_iterable_type)
else:
if_types.append(possible_iterable_type)
else_types.append(possible_iterable_type)
return (
UnionType.make_union(if_types) if if_types else None,
UnionType.make_union(else_types) if else_types else None,
)
def _is_truthy_type(self, t: ProperType) -> bool:
return (
(
isinstance(t, Instance)
and bool(t.type)
and not t.type.has_readable_member("__bool__")
and not t.type.has_readable_member("__len__")
and t.type.fullname != "builtins.object"
)
or isinstance(t, FunctionLike)
or (
isinstance(t, UnionType)
and all(self._is_truthy_type(t) for t in get_proper_types(t.items))
)
)
def check_for_truthy_type(self, t: Type, expr: Expression) -> None:
"""
Check if a type can have a truthy value.
Used in checks like::
if x: # <---
not x # <---
"""
if not state.strict_optional:
return # if everything can be None, all bets are off
t = get_proper_type(t)
if not self._is_truthy_type(t):
return
def format_expr_type() -> str:
typ = format_type(t, self.options)
if isinstance(expr, MemberExpr):
return f'Member "{expr.name}" has type {typ}'
elif isinstance(expr, RefExpr) and expr.fullname:
return f'"{expr.fullname}" has type {typ}'
elif isinstance(expr, CallExpr):
if isinstance(expr.callee, MemberExpr):
return f'"{expr.callee.name}" returns {typ}'
elif isinstance(expr.callee, RefExpr) and expr.callee.fullname:
return f'"{expr.callee.fullname}" returns {typ}'
return f"Call returns {typ}"
else:
return f"Expression has type {typ}"
def get_expr_name() -> str:
if isinstance(expr, (NameExpr, MemberExpr)):
return f'"{expr.name}"'
else:
# return type if expr has no name
return format_type(t, self.options)
if isinstance(t, FunctionLike):
self.fail(message_registry.FUNCTION_ALWAYS_TRUE.format(get_expr_name()), expr)
elif isinstance(t, UnionType):
self.fail(message_registry.TYPE_ALWAYS_TRUE_UNIONTYPE.format(format_expr_type()), expr)
elif isinstance(t, Instance) and t.type.fullname == "typing.Iterable":
_, info = self.make_fake_typeinfo("typing", "Collection", "Collection", [])
self.fail(
message_registry.ITERABLE_ALWAYS_TRUE.format(
format_expr_type(), format_type(Instance(info, t.args), self.options)
),
expr,
)
else:
self.fail(message_registry.TYPE_ALWAYS_TRUE.format(format_expr_type()), expr)
def find_type_equals_check(
self, node: ComparisonExpr, expr_indices: list[int]
) -> tuple[TypeMap, TypeMap]:
"""Narrow types based on any checks of the type ``type(x) == T``
Args:
node: The node that might contain the comparison
expr_indices: The list of indices of expressions in ``node`` that are being
compared
"""
def is_type_call(expr: CallExpr) -> bool:
"""Is expr a call to type with one argument?"""
return refers_to_fullname(expr.callee, "builtins.type") and len(expr.args) == 1
# exprs that are being passed into type
exprs_in_type_calls: list[Expression] = []
# type that is being compared to type(expr)
type_being_compared: list[TypeRange] | None = None
# whether the type being compared to is final
is_final = False
for index in expr_indices:
expr = node.operands[index]
if isinstance(expr, CallExpr) and is_type_call(expr):
exprs_in_type_calls.append(expr.args[0])
else:
current_type = self.get_isinstance_type(expr)
if current_type is None:
continue
if type_being_compared is not None:
# It doesn't really make sense to have several types being
# compared to the output of type (like type(x) == int == str)
# because whether that's true is solely dependent on what the
# types being compared are, so we don't try to narrow types any
# further because we can't really get any information about the
# type of x from that check
return {}, {}
else:
if isinstance(expr, RefExpr) and isinstance(expr.node, TypeInfo):
is_final = expr.node.is_final
type_being_compared = current_type
if not exprs_in_type_calls:
return {}, {}
if_maps: list[TypeMap] = []
else_maps: list[TypeMap] = []
for expr in exprs_in_type_calls:
current_if_type, current_else_type = self.conditional_types_with_intersection(
self.lookup_type(expr), type_being_compared, expr
)
current_if_map, current_else_map = conditional_types_to_typemaps(
expr, current_if_type, current_else_type
)
if_maps.append(current_if_map)
else_maps.append(current_else_map)
def combine_maps(list_maps: list[TypeMap]) -> TypeMap:
"""Combine all typemaps in list_maps into one typemap"""
if all(m is None for m in list_maps):
return None
result_map = {}
for d in list_maps:
if d is not None:
result_map.update(d)
return result_map
if_map = combine_maps(if_maps)
# type(x) == T is only true when x has the same type as T, meaning
# that it can be false if x is an instance of a subclass of T. That means
# we can't do any narrowing in the else case unless T is final, in which
# case T can't be subclassed
if is_final:
else_map = combine_maps(else_maps)
else:
else_map = {}
return if_map, else_map
def find_isinstance_check(
self, node: Expression, *, in_boolean_context: bool = True
) -> tuple[TypeMap, TypeMap]:
"""Find any isinstance checks (within a chain of ands). Includes
implicit and explicit checks for None and calls to callable.
Also includes TypeGuard and TypeIs functions.
Return value is a map of variables to their types if the condition
is true and a map of variables to their types if the condition is false.
If either of the values in the tuple is None, then that particular
branch can never occur.
If `in_boolean_context=True` is passed, it means that we handle
a walrus expression. We treat rhs values
in expressions like `(a := A())` specially:
for example, some errors are suppressed.
May return {}, {}.
Can return None, None in situations involving NoReturn.
"""
if_map, else_map = self.find_isinstance_check_helper(
node, in_boolean_context=in_boolean_context
)
new_if_map = self.propagate_up_typemap_info(if_map)
new_else_map = self.propagate_up_typemap_info(else_map)
return new_if_map, new_else_map
def find_isinstance_check_helper(
self, node: Expression, *, in_boolean_context: bool = True
) -> tuple[TypeMap, TypeMap]:
if is_true_literal(node):
return {}, None
if is_false_literal(node):
return None, {}
if isinstance(node, CallExpr) and len(node.args) != 0:
expr = collapse_walrus(node.args[0])
if refers_to_fullname(node.callee, "builtins.isinstance"):
if len(node.args) != 2: # the error will be reported elsewhere
return {}, {}
if literal(expr) == LITERAL_TYPE:
return conditional_types_to_typemaps(
expr,
*self.conditional_types_with_intersection(
self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr
),
)
elif refers_to_fullname(node.callee, "builtins.issubclass"):
if len(node.args) != 2: # the error will be reported elsewhere
return {}, {}
if literal(expr) == LITERAL_TYPE:
return self.infer_issubclass_maps(node, expr)
elif refers_to_fullname(node.callee, "builtins.callable"):
if len(node.args) != 1: # the error will be reported elsewhere
return {}, {}
if literal(expr) == LITERAL_TYPE:
vartype = self.lookup_type(expr)
return self.conditional_callable_type_map(expr, vartype)
elif refers_to_fullname(node.callee, "builtins.hasattr"):
if len(node.args) != 2: # the error will be reported elsewhere
return {}, {}
attr = try_getting_str_literals(node.args[1], self.lookup_type(node.args[1]))
if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1:
return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0])
else:
type_is, type_guard = None, None
called_type = self.lookup_type_or_none(node.callee)
if called_type is not None:
called_type = get_proper_type(called_type)
# TODO: there are some more cases in check_call() to handle.
# If the callee is an instance, try to extract TypeGuard/TypeIs from its __call__ method.
if isinstance(called_type, Instance):
call = find_member("__call__", called_type, called_type, is_operator=True)
if call is not None:
called_type = get_proper_type(call)
if isinstance(called_type, CallableType):
type_is, type_guard = called_type.type_is, called_type.type_guard
# If the callee is a RefExpr, extract TypeGuard/TypeIs directly.
if isinstance(node.callee, RefExpr):
type_is, type_guard = node.callee.type_is, node.callee.type_guard
if type_guard is not None or type_is is not None:
# TODO: Follow *args, **kwargs
if node.arg_kinds[0] != nodes.ARG_POS:
# *assuming* the overloaded function is correct, there's a couple cases:
# 1) The first argument has different names, but is pos-only. We don't
# care about this case, the argument must be passed positionally.
# 2) The first argument allows keyword reference, therefore must be the
# same between overloads.
if isinstance(called_type, (CallableType, Overloaded)):
name = called_type.items[0].arg_names[0]
if name in node.arg_names:
idx = node.arg_names.index(name)
# we want the idx-th variable to be narrowed
expr = collapse_walrus(node.args[idx])
else:
kind = "guard" if type_guard is not None else "narrower"
self.fail(
message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node
)
return {}, {}
if literal(expr) == LITERAL_TYPE:
# Note: we wrap the target type, so that we can special case later.
# Namely, for isinstance() we use a normal meet, while TypeGuard is
# considered "always right" (i.e. even if the types are not overlapping).
# Also note that a care must be taken to unwrap this back at read places
# where we use this to narrow down declared type.
if type_guard is not None:
return {expr: TypeGuardedType(type_guard)}, {}
else:
assert type_is is not None
return conditional_types_to_typemaps(
expr,
*self.conditional_types_with_intersection(
self.lookup_type(expr),
[TypeRange(type_is, is_upper_bound=False)],
expr,
consider_runtime_isinstance=False,
),
)
elif isinstance(node, ComparisonExpr):
return self.comparison_type_narrowing_helper(node)
elif isinstance(node, AssignmentExpr):
if_map: dict[Expression, Type] | None
else_map: dict[Expression, Type] | None
if_map = {}
else_map = {}
if_assignment_map, else_assignment_map = self.find_isinstance_check(node.target)
if if_assignment_map is not None:
if_map.update(if_assignment_map)
if else_assignment_map is not None:
else_map.update(else_assignment_map)
if_condition_map, else_condition_map = self.find_isinstance_check(
node.value, in_boolean_context=False
)
if if_condition_map is not None:
if_map.update(if_condition_map)
if else_condition_map is not None:
else_map.update(else_condition_map)
return (
(None if if_assignment_map is None or if_condition_map is None else if_map),
(None if else_assignment_map is None or else_condition_map is None else else_map),
)
elif isinstance(node, OpExpr) and node.op == "and":
left_if_vars, left_else_vars = self.find_isinstance_check(node.left)
right_if_vars, right_else_vars = self.find_isinstance_check(node.right)
# (e1 and e2) is true if both e1 and e2 are true,
# and false if at least one of e1 and e2 is false.
return (
and_conditional_maps(left_if_vars, right_if_vars),
# Note that if left else type is Any, we can't add any additional
# types to it, since the right maps were computed assuming
# the left is True, which may be not the case in the else branch.
or_conditional_maps(left_else_vars, right_else_vars, coalesce_any=True),
)
elif isinstance(node, OpExpr) and node.op == "or":
left_if_vars, left_else_vars = self.find_isinstance_check(node.left)
right_if_vars, right_else_vars = self.find_isinstance_check(node.right)
# (e1 or e2) is true if at least one of e1 or e2 is true,
# and false if both e1 and e2 are false.
return (
or_conditional_maps(left_if_vars, right_if_vars),
and_conditional_maps(left_else_vars, right_else_vars),
)
elif isinstance(node, UnaryExpr) and node.op == "not":
left, right = self.find_isinstance_check(node.expr)
return right, left
elif (
literal(node) == LITERAL_TYPE
and self.has_type(node)
and self.can_be_narrowed_with_len(self.lookup_type(node))
# Only translate `if x` to `if len(x) > 0` when possible.
and not custom_special_method(self.lookup_type(node), "__bool__")
and self.options.strict_optional
):
# Combine a `len(x) > 0` check with the default logic below.
yes_type, no_type = self.narrow_with_len(self.lookup_type(node), ">", 0)
if yes_type is not None:
yes_type = true_only(yes_type)
else:
yes_type = UninhabitedType()
if no_type is not None:
no_type = false_only(no_type)
else:
no_type = UninhabitedType()
if_map = {node: yes_type} if not isinstance(yes_type, UninhabitedType) else None
else_map = {node: no_type} if not isinstance(no_type, UninhabitedType) else None
return if_map, else_map
# Restrict the type of the variable to True-ish/False-ish in the if and else branches
# respectively
original_vartype = self.lookup_type(node)
if in_boolean_context:
# We don't check `:=` values in expressions like `(a := A())`,
# because they produce two error messages.
self.check_for_truthy_type(original_vartype, node)
vartype = try_expanding_sum_type_to_union(original_vartype, "builtins.bool")
if_type = true_only(vartype)
else_type = false_only(vartype)
if_map = {node: if_type} if not isinstance(if_type, UninhabitedType) else None
else_map = {node: else_type} if not isinstance(else_type, UninhabitedType) else None
return if_map, else_map
def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMap, TypeMap]:
"""Infer type narrowing from a comparison expression."""
# Step 1: Obtain the types of each operand and whether or not we can
# narrow their types. (For example, we shouldn't try narrowing the
# types of literal string or enum expressions).
operands = [collapse_walrus(x) for x in node.operands]
operand_types = []
narrowable_operand_index_to_hash = {}
for i, expr in enumerate(operands):
if not self.has_type(expr):
return {}, {}
expr_type = self.lookup_type(expr)
operand_types.append(expr_type)
if (
literal(expr) == LITERAL_TYPE
and not is_literal_none(expr)
and not self.is_literal_enum(expr)
):
h = literal_hash(expr)
if h is not None:
narrowable_operand_index_to_hash[i] = h
# Step 2: Group operands chained by either the 'is' or '==' operands
# together. For all other operands, we keep them in groups of size 2.
# So the expression:
#
# x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8
#
# ...is converted into the simplified operator list:
#
# [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]),
# ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])]
#
# We group identity/equality expressions so we can propagate information
# we discover about one operand across the entire chain. We don't bother
# handling 'is not' and '!=' chains in a special way: those are very rare
# in practice.
simplified_operator_list = group_comparison_operands(
node.pairwise(), narrowable_operand_index_to_hash, {"==", "is"}
)
# Step 3: Analyze each group and infer more precise type maps for each
# assignable operand, if possible. We combine these type maps together
# in the final step.
partial_type_maps = []
for operator, expr_indices in simplified_operator_list:
if operator in {"is", "is not", "==", "!="}:
if_map, else_map = self.equality_type_narrowing_helper(
node,
operator,
operands,
operand_types,
expr_indices,
narrowable_operand_index_to_hash,
)
elif operator in {"in", "not in"}:
assert len(expr_indices) == 2
left_index, right_index = expr_indices
item_type = operand_types[left_index]
iterable_type = operand_types[right_index]
if_map, else_map = {}, {}
if left_index in narrowable_operand_index_to_hash:
# We only try and narrow away 'None' for now
if is_overlapping_none(item_type):
collection_item_type = get_proper_type(builtin_item_type(iterable_type))
if (
collection_item_type is not None
and not is_overlapping_none(collection_item_type)
and not (
isinstance(collection_item_type, Instance)
and collection_item_type.type.fullname == "builtins.object"
)
and is_overlapping_erased_types(item_type, collection_item_type)
):
if_map[operands[left_index]] = remove_optional(item_type)
if right_index in narrowable_operand_index_to_hash:
if_type, else_type = self.conditional_types_for_iterable(
item_type, iterable_type
)
expr = operands[right_index]
if if_type is None:
if_map = None
else:
if_map[expr] = if_type
if else_type is None:
else_map = None
else:
else_map[expr] = else_type
else:
if_map = {}
else_map = {}
if operator in {"is not", "!=", "not in"}:
if_map, else_map = else_map, if_map
partial_type_maps.append((if_map, else_map))
# If we have found non-trivial restrictions from the regular comparisons,
# then return soon. Otherwise try to infer restrictions involving `len(x)`.
# TODO: support regular and len() narrowing in the same chain.
if any(m != ({}, {}) for m in partial_type_maps):
return reduce_conditional_maps(partial_type_maps)
else:
# Use meet for `and` maps to get correct results for chained checks
# like `if 1 < len(x) < 4: ...`
return reduce_conditional_maps(self.find_tuple_len_narrowing(node), use_meet=True)
def equality_type_narrowing_helper(
self,
node: ComparisonExpr,
operator: str,
operands: list[Expression],
operand_types: list[Type],
expr_indices: list[int],
narrowable_operand_index_to_hash: dict[int, tuple[Key, ...]],
) -> tuple[TypeMap, TypeMap]:
"""Calculate type maps for '==', '!=', 'is' or 'is not' expression."""
# is_valid_target:
# Controls which types we're allowed to narrow exprs to. Note that
# we cannot use 'is_literal_type_like' in both cases since doing
# 'x = 10000 + 1; x is 10001' is not always True in all Python
# implementations.
#
# coerce_only_in_literal_context:
# If true, coerce types into literal types only if one or more of
# the provided exprs contains an explicit Literal type. This could
# technically be set to any arbitrary value, but it seems being liberal
# with narrowing when using 'is' and conservative when using '==' seems
# to break the least amount of real-world code.
#
# should_narrow_by_identity:
# Set to 'false' only if the user defines custom __eq__ or __ne__ methods
# that could cause identity-based narrowing to produce invalid results.
if operator in {"is", "is not"}:
is_valid_target: Callable[[Type], bool] = is_singleton_type
coerce_only_in_literal_context = False
should_narrow_by_identity = True
else:
def is_exactly_literal_type(t: Type) -> bool:
return isinstance(get_proper_type(t), LiteralType)
def has_no_custom_eq_checks(t: Type) -> bool:
return not custom_special_method(
t, "__eq__", check_all=False
) and not custom_special_method(t, "__ne__", check_all=False)
is_valid_target = is_exactly_literal_type
coerce_only_in_literal_context = True
expr_types = [operand_types[i] for i in expr_indices]
should_narrow_by_identity = all(
map(has_no_custom_eq_checks, expr_types)
) and not is_ambiguous_mix_of_enums(expr_types)
if_map: TypeMap = {}
else_map: TypeMap = {}
if should_narrow_by_identity:
if_map, else_map = self.refine_identity_comparison_expression(
operands,
operand_types,
expr_indices,
narrowable_operand_index_to_hash.keys(),
is_valid_target,
coerce_only_in_literal_context,
)
if if_map == {} and else_map == {}:
if_map, else_map = self.refine_away_none_in_comparison(
operands, operand_types, expr_indices, narrowable_operand_index_to_hash.keys()
)
# If we haven't been able to narrow types yet, we might be dealing with a
# explicit type(x) == some_type check
if if_map == {} and else_map == {}:
if_map, else_map = self.find_type_equals_check(node, expr_indices)
return if_map, else_map
def propagate_up_typemap_info(self, new_types: TypeMap) -> TypeMap:
"""Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types.
Specifically, this function accepts two mappings of expression to original types:
the original mapping (existing_types), and a new mapping (new_types) intended to
update the original.
This function iterates through new_types and attempts to use the information to try
refining any parent types that happen to be unions.
For example, suppose there are two types "A = Tuple[int, int]" and "B = Tuple[str, str]".
Next, suppose that 'new_types' specifies the expression 'foo[0]' has a refined type
of 'int' and that 'foo' was previously deduced to be of type Union[A, B].
Then, this function will observe that since A[0] is an int and B[0] is not, the type of
'foo' can be further refined from Union[A, B] into just B.
We perform this kind of "parent narrowing" for member lookup expressions and indexing
expressions into tuples, namedtuples, and typeddicts. We repeat this narrowing
recursively if the parent is also a "lookup expression". So for example, if we have
the expression "foo['bar'].baz[0]", we'd potentially end up refining types for the
expressions "foo", "foo['bar']", and "foo['bar'].baz".
We return the newly refined map. This map is guaranteed to be a superset of 'new_types'.
"""
if new_types is None:
return None
output_map = {}
for expr, expr_type in new_types.items():
# The original inferred type should always be present in the output map, of course
output_map[expr] = expr_type
# Next, try using this information to refine the parent types, if applicable.
new_mapping = self.refine_parent_types(expr, expr_type)
for parent_expr, proposed_parent_type in new_mapping.items():
# We don't try inferring anything if we've already inferred something for
# the parent expression.
# TODO: Consider picking the narrower type instead of always discarding this?
if parent_expr in new_types:
continue
output_map[parent_expr] = proposed_parent_type
return output_map
def refine_parent_types(self, expr: Expression, expr_type: Type) -> Mapping[Expression, Type]:
"""Checks if the given expr is a 'lookup operation' into a union and iteratively refines
the parent types based on the 'expr_type'.
For example, if 'expr' is an expression like 'a.b.c.d', we'll potentially return refined
types for expressions 'a', 'a.b', and 'a.b.c'.
For more details about what a 'lookup operation' is and how we use the expr_type to refine
the parent types of lookup_expr, see the docstring in 'propagate_up_typemap_info'.
"""
output: dict[Expression, Type] = {}
# Note: parent_expr and parent_type are progressively refined as we crawl up the
# parent lookup chain.
while True:
# First, check if this expression is one that's attempting to
# "lookup" some key in the parent type. If so, save the parent type
# and create function that will try replaying the same lookup
# operation against arbitrary types.
if isinstance(expr, MemberExpr):
parent_expr = self._propagate_walrus_assignments(expr.expr, output)
parent_type = self.lookup_type_or_none(parent_expr)
member_name = expr.name
def replay_lookup(new_parent_type: ProperType) -> Type | None:
with self.msg.filter_errors() as w:
member_type = analyze_member_access(
name=member_name,
typ=new_parent_type,
context=parent_expr,
is_lvalue=False,
is_super=False,
is_operator=False,
original_type=new_parent_type,
chk=self,
in_literal_context=False,
)
if w.has_new_errors():
return None
else:
return member_type
elif isinstance(expr, IndexExpr):
parent_expr = self._propagate_walrus_assignments(expr.base, output)
parent_type = self.lookup_type_or_none(parent_expr)
self._propagate_walrus_assignments(expr.index, output)
index_type = self.lookup_type_or_none(expr.index)
if index_type is None:
return output
str_literals = try_getting_str_literals_from_type(index_type)
if str_literals is not None:
# Refactoring these two indexing replay functions is surprisingly
# tricky -- see https://github.com/python/mypy/pull/7917, which
# was blocked by https://github.com/mypyc/mypyc/issues/586
def replay_lookup(new_parent_type: ProperType) -> Type | None:
if not isinstance(new_parent_type, TypedDictType):
return None
try:
assert str_literals is not None
member_types = [new_parent_type.items[key] for key in str_literals]
except KeyError:
return None
return make_simplified_union(member_types)
else:
int_literals = try_getting_int_literals_from_type(index_type)
if int_literals is not None:
def replay_lookup(new_parent_type: ProperType) -> Type | None:
if not isinstance(new_parent_type, TupleType):
return None
try:
assert int_literals is not None
member_types = [new_parent_type.items[key] for key in int_literals]
except IndexError:
return None
return make_simplified_union(member_types)
else:
return output
else:
return output
# If we somehow didn't previously derive the parent type, abort completely
# with what we have so far: something went wrong at an earlier stage.
if parent_type is None:
return output
# We currently only try refining the parent type if it's a Union.
# If not, there's no point in trying to refine any further parents
# since we have no further information we can use to refine the lookup
# chain, so we end early as an optimization.
parent_type = get_proper_type(parent_type)
if not isinstance(parent_type, UnionType):
return output
# Take each element in the parent union and replay the original lookup procedure
# to figure out which parents are compatible.
new_parent_types = []
for item in flatten_nested_unions(parent_type.items):
member_type = replay_lookup(get_proper_type(item))
if member_type is None:
# We were unable to obtain the member type. So, we give up on refining this
# parent type entirely and abort.
return output
if is_overlapping_types(member_type, expr_type):
new_parent_types.append(item)
# If none of the parent types overlap (if we derived an empty union), something
# went wrong. We should never hit this case, but deriving the uninhabited type or
# reporting an error both seem unhelpful. So we abort.
if not new_parent_types:
return output
expr = parent_expr
expr_type = output[parent_expr] = make_simplified_union(new_parent_types)
def _propagate_walrus_assignments(
self, expr: Expression, type_map: dict[Expression, Type]
) -> Expression:
"""Add assignments from walrus expressions to inferred types.
Only considers nested assignment exprs, does not recurse into other types.
This may be added later if necessary by implementing a dedicated visitor.
"""
if isinstance(expr, AssignmentExpr):
if isinstance(expr.value, AssignmentExpr):
self._propagate_walrus_assignments(expr.value, type_map)
assigned_type = self.lookup_type_or_none(expr.value)
parent_expr = collapse_walrus(expr)
if assigned_type is not None:
type_map[parent_expr] = assigned_type
return parent_expr
return expr
def refine_identity_comparison_expression(
self,
operands: list[Expression],
operand_types: list[Type],
chain_indices: list[int],
narrowable_operand_indices: AbstractSet[int],
is_valid_target: Callable[[ProperType], bool],
coerce_only_in_literal_context: bool,
) -> tuple[TypeMap, TypeMap]:
"""Produce conditional type maps refining expressions by an identity/equality comparison.
The 'operands' and 'operand_types' lists should be the full list of operands used
in the overall comparison expression. The 'chain_indices' list is the list of indices
actually used within this identity comparison chain.
So if we have the expression:
a <= b is c is d <= e
...then 'operands' and 'operand_types' would be lists of length 5 and 'chain_indices'
would be the list [1, 2, 3].
The 'narrowable_operand_indices' parameter is the set of all indices we are allowed
to refine the types of: that is, all operands that will potentially be a part of
the output TypeMaps.
Although this function could theoretically try setting the types of the operands
in the chains to the meet, doing that causes too many issues in real-world code.
Instead, we use 'is_valid_target' to identify which of the given chain types
we could plausibly use as the refined type for the expressions in the chain.
Similarly, 'coerce_only_in_literal_context' controls whether we should try coercing
expressions in the chain to a Literal type. Performing this coercion is sometimes
too aggressive of a narrowing, depending on context.
"""
should_coerce = True
if coerce_only_in_literal_context:
def should_coerce_inner(typ: Type) -> bool:
typ = get_proper_type(typ)
return is_literal_type_like(typ) or (
isinstance(typ, Instance) and typ.type.is_enum
)
should_coerce = any(should_coerce_inner(operand_types[i]) for i in chain_indices)
target: Type | None = None
possible_target_indices = []
for i in chain_indices:
expr_type = operand_types[i]
if should_coerce:
expr_type = coerce_to_literal(expr_type)
if not is_valid_target(get_proper_type(expr_type)):
continue
if target and not is_same_type(target, expr_type):
# We have multiple disjoint target types. So the 'if' branch
# must be unreachable.
return None, {}
target = expr_type
possible_target_indices.append(i)
# There's nothing we can currently infer if none of the operands are valid targets,
# so we end early and infer nothing.
if target is None:
return {}, {}
# If possible, use an unassignable expression as the target.
# We skip refining the type of the target below, so ideally we'd
# want to pick an expression we were going to skip anyways.
singleton_index = -1
for i in possible_target_indices:
if i not in narrowable_operand_indices:
singleton_index = i
# But if none of the possible singletons are unassignable ones, we give up
# and arbitrarily pick the last item, mostly because other parts of the
# type narrowing logic bias towards picking the rightmost item and it'd be
# nice to stay consistent.
#
# That said, it shouldn't matter which index we pick. For example, suppose we
# have this if statement, where 'x' and 'y' both have singleton types:
#
# if x is y:
# reveal_type(x)
# reveal_type(y)
# else:
# reveal_type(x)
# reveal_type(y)
#
# At this point, 'x' and 'y' *must* have the same singleton type: we would have
# ended early in the first for-loop in this function if they weren't.
#
# So, we should always get the same result in the 'if' case no matter which
# index we pick. And while we do end up getting different results in the 'else'
# case depending on the index (e.g. if we pick 'y', then its type stays the same
# while 'x' is narrowed to '<uninhabited>'), this distinction is also moot: mypy
# currently will just mark the whole branch as unreachable if either operand is
# narrowed to <uninhabited>.
if singleton_index == -1:
singleton_index = possible_target_indices[-1]
sum_type_name = None
target = get_proper_type(target)
if isinstance(target, LiteralType) and (
target.is_enum_literal() or isinstance(target.value, bool)
):
sum_type_name = target.fallback.type.fullname
target_type = [TypeRange(target, is_upper_bound=False)]
partial_type_maps = []
for i in chain_indices:
# If we try refining a type against itself, conditional_type_map
# will end up assuming that the 'else' branch is unreachable. This is
# typically not what we want: generally the user will intend for the
# target type to be some fixed 'sentinel' value and will want to refine
# the other exprs against this one instead.
if i == singleton_index:
continue
# Naturally, we can't refine operands which are not permitted to be refined.
if i not in narrowable_operand_indices:
continue
expr = operands[i]
expr_type = coerce_to_literal(operand_types[i])
if sum_type_name is not None:
expr_type = try_expanding_sum_type_to_union(expr_type, sum_type_name)
# We intentionally use 'conditional_types' directly here instead of
# 'self.conditional_types_with_intersection': we only compute ad-hoc
# intersections when working with pure instances.
types = conditional_types(expr_type, target_type)
partial_type_maps.append(conditional_types_to_typemaps(expr, *types))
return reduce_conditional_maps(partial_type_maps)
def refine_away_none_in_comparison(
self,
operands: list[Expression],
operand_types: list[Type],
chain_indices: list[int],
narrowable_operand_indices: AbstractSet[int],
) -> tuple[TypeMap, TypeMap]:
"""Produces conditional type maps refining away None in an identity/equality chain.
For more details about what the different arguments mean, see the
docstring of 'refine_identity_comparison_expression' up above.
"""
non_optional_types = []
for i in chain_indices:
typ = operand_types[i]
if not is_overlapping_none(typ):
non_optional_types.append(typ)
if_map, else_map = {}, {}
if not non_optional_types or (len(non_optional_types) != len(chain_indices)):
# Narrow e.g. `Optional[A] == "x"` or `Optional[A] is "x"` to `A` (which may be
# convenient but is strictly not type-safe):
for i in narrowable_operand_indices:
expr_type = operand_types[i]
if not is_overlapping_none(expr_type):
continue
if any(is_overlapping_erased_types(expr_type, t) for t in non_optional_types):
if_map[operands[i]] = remove_optional(expr_type)
# Narrow e.g. `Optional[A] != None` to `A` (which is stricter than the above step and
# so type-safe but less convenient, because e.g. `Optional[A] == None` still results
# in `Optional[A]`):
if any(isinstance(get_proper_type(ot), NoneType) for ot in operand_types):
for i in narrowable_operand_indices:
expr_type = operand_types[i]
if is_overlapping_none(expr_type):
else_map[operands[i]] = remove_optional(expr_type)
return if_map, else_map
def is_len_of_tuple(self, expr: Expression) -> bool:
"""Is this expression a `len(x)` call where x is a tuple or union of tuples?"""
if not isinstance(expr, CallExpr):
return False
if not refers_to_fullname(expr.callee, "builtins.len"):
return False
if len(expr.args) != 1:
return False
expr = expr.args[0]
if literal(expr) != LITERAL_TYPE:
return False
if not self.has_type(expr):
return False
return self.can_be_narrowed_with_len(self.lookup_type(expr))
def can_be_narrowed_with_len(self, typ: Type) -> bool:
"""Is this a type that can benefit from length check type restrictions?
Currently supported types are TupleTypes, Instances of builtins.tuple, and
unions involving such types.
"""
if custom_special_method(typ, "__len__"):
# If user overrides builtin behavior, we can't do anything.
return False
p_typ = get_proper_type(typ)
# Note: we are conservative about tuple subclasses, because some code may rely on
# the fact that tuple_type of fallback TypeInfo matches the original TupleType.
if isinstance(p_typ, TupleType):
if any(isinstance(t, UnpackType) for t in p_typ.items):
return p_typ.partial_fallback.type.fullname == "builtins.tuple"
return True
if isinstance(p_typ, Instance):
return p_typ.type.has_base("builtins.tuple")
if isinstance(p_typ, UnionType):
return any(self.can_be_narrowed_with_len(t) for t in p_typ.items)
return False
def literal_int_expr(self, expr: Expression) -> int | None:
"""Is this expression an int literal, or a reference to an int constant?
If yes, return the corresponding int value, otherwise return None.
"""
if not self.has_type(expr):
return None
expr_type = self.lookup_type(expr)
expr_type = coerce_to_literal(expr_type)
proper_type = get_proper_type(expr_type)
if not isinstance(proper_type, LiteralType):
return None
if not isinstance(proper_type.value, int):
return None
return proper_type.value
def find_tuple_len_narrowing(self, node: ComparisonExpr) -> list[tuple[TypeMap, TypeMap]]:
"""Top-level logic to find type restrictions from a length check on tuples.
We try to detect `if` checks like the following:
x: tuple[int, int] | tuple[int, int, int]
y: tuple[int, int] | tuple[int, int, int]
if len(x) == len(y) == 2:
a, b = x # OK
c, d = y # OK
z: tuple[int, ...]
if 1 < len(z) < 4:
x = z # OK
and report corresponding type restrictions to the binder.
"""
# First step: group consecutive `is` and `==` comparisons together.
# This is essentially a simplified version of group_comparison_operands(),
# tuned to the len()-like checks. Note that we don't propagate indirect
# restrictions like e.g. `len(x) > foo() > 1` yet, since it is tricky.
# TODO: propagate indirect len() comparison restrictions.
chained = []
last_group = set()
for op, left, right in node.pairwise():
if isinstance(left, AssignmentExpr):
left = left.value
if isinstance(right, AssignmentExpr):
right = right.value
if op in ("is", "=="):
last_group.add(left)
last_group.add(right)
else:
if last_group:
chained.append(("==", list(last_group)))
last_group = set()
if op in {"is not", "!=", "<", "<=", ">", ">="}:
chained.append((op, [left, right]))
if last_group:
chained.append(("==", list(last_group)))
# Second step: infer type restrictions from each group found above.
type_maps = []
for op, items in chained:
# TODO: support unions of literal types as len() comparison targets.
if not any(self.literal_int_expr(it) is not None for it in items):
continue
if not any(self.is_len_of_tuple(it) for it in items):
continue
# At this step we know there is at least one len(x) and one literal in the group.
if op in ("is", "=="):
literal_values = set()
tuples = []
for it in items:
lit = self.literal_int_expr(it)
if lit is not None:
literal_values.add(lit)
continue
if self.is_len_of_tuple(it):
assert isinstance(it, CallExpr)
tuples.append(it.args[0])
if len(literal_values) > 1:
# More than one different literal value found, like 1 == len(x) == 2,
# so the corresponding branch is unreachable.
return [(None, {})]
size = literal_values.pop()
if size > MAX_PRECISE_TUPLE_SIZE:
# Avoid creating huge tuples from checks like if len(x) == 300.
continue
for tpl in tuples:
yes_type, no_type = self.narrow_with_len(self.lookup_type(tpl), op, size)
yes_map = None if yes_type is None else {tpl: yes_type}
no_map = None if no_type is None else {tpl: no_type}
type_maps.append((yes_map, no_map))
else:
left, right = items
if self.is_len_of_tuple(right):
# Normalize `1 < len(x)` and similar as `len(x) > 1`.
left, right = right, left
op = flip_ops.get(op, op)
r_size = self.literal_int_expr(right)
assert r_size is not None
if r_size > MAX_PRECISE_TUPLE_SIZE:
# Avoid creating huge unions from checks like if len(x) > 300.
continue
assert isinstance(left, CallExpr)
yes_type, no_type = self.narrow_with_len(
self.lookup_type(left.args[0]), op, r_size
)
yes_map = None if yes_type is None else {left.args[0]: yes_type}
no_map = None if no_type is None else {left.args[0]: no_type}
type_maps.append((yes_map, no_map))
return type_maps
def narrow_with_len(self, typ: Type, op: str, size: int) -> tuple[Type | None, Type | None]:
"""Dispatch tuple type narrowing logic depending on the kind of type we got."""
typ = get_proper_type(typ)
if isinstance(typ, TupleType):
return self.refine_tuple_type_with_len(typ, op, size)
elif isinstance(typ, Instance):
return self.refine_instance_type_with_len(typ, op, size)
elif isinstance(typ, UnionType):
yes_types = []
no_types = []
other_types = []
for t in typ.items:
if not self.can_be_narrowed_with_len(t):
other_types.append(t)
continue
yt, nt = self.narrow_with_len(t, op, size)
if yt is not None:
yes_types.append(yt)
if nt is not None:
no_types.append(nt)
yes_types += other_types
no_types += other_types
if yes_types:
yes_type = make_simplified_union(yes_types)
else:
yes_type = None
if no_types:
no_type = make_simplified_union(no_types)
else:
no_type = None
return yes_type, no_type
else:
assert False, "Unsupported type for len narrowing"
def refine_tuple_type_with_len(
self, typ: TupleType, op: str, size: int
) -> tuple[Type | None, Type | None]:
"""Narrow a TupleType using length restrictions."""
unpack_index = find_unpack_in_list(typ.items)
if unpack_index is None:
# For fixed length tuple situation is trivial, it is either reachable or not,
# depending on the current length, expected length, and the comparison op.
method = int_op_to_method[op]
if method(typ.length(), size):
return typ, None
return None, typ
unpack = typ.items[unpack_index]
assert isinstance(unpack, UnpackType)
unpacked = get_proper_type(unpack.type)
if isinstance(unpacked, TypeVarTupleType):
# For tuples involving TypeVarTuple unpack we can't do much except
# inferring reachability, and recording the restrictions on TypeVarTuple
# for further "manual" use elsewhere.
min_len = typ.length() - 1 + unpacked.min_len
if op in ("==", "is"):
if min_len <= size:
return typ, typ
return None, typ
elif op in ("<", "<="):
if op == "<=":
size += 1
if min_len < size:
prefix = typ.items[:unpack_index]
suffix = typ.items[unpack_index + 1 :]
# TODO: also record max_len to avoid false negatives?
unpack = UnpackType(unpacked.copy_modified(min_len=size - typ.length() + 1))
return typ, typ.copy_modified(items=prefix + [unpack] + suffix)
return None, typ
else:
yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size)
return no_type, yes_type
# Homogeneous variadic item is the case where we are most flexible. Essentially,
# we adjust the variadic item by "eating away" from it to satisfy the restriction.
assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple"
min_len = typ.length() - 1
arg = unpacked.args[0]
prefix = typ.items[:unpack_index]
suffix = typ.items[unpack_index + 1 :]
if op in ("==", "is"):
if min_len <= size:
# TODO: return fixed union + prefixed variadic tuple for no_type?
return typ.copy_modified(items=prefix + [arg] * (size - min_len) + suffix), typ
return None, typ
elif op in ("<", "<="):
if op == "<=":
size += 1
if min_len < size:
# Note: there is some ambiguity w.r.t. to where to put the additional
# items: before or after the unpack. However, such types are equivalent,
# so we always put them before for consistency.
no_type = typ.copy_modified(
items=prefix + [arg] * (size - min_len) + [unpack] + suffix
)
yes_items = []
for n in range(size - min_len):
yes_items.append(typ.copy_modified(items=prefix + [arg] * n + suffix))
return UnionType.make_union(yes_items, typ.line, typ.column), no_type
return None, typ
else:
yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size)
return no_type, yes_type
def refine_instance_type_with_len(
self, typ: Instance, op: str, size: int
) -> tuple[Type | None, Type | None]:
"""Narrow a homogeneous tuple using length restrictions."""
base = map_instance_to_supertype(typ, self.lookup_typeinfo("builtins.tuple"))
arg = base.args[0]
# Again, we are conservative about subclasses until we gain more confidence.
allow_precise = (
PRECISE_TUPLE_TYPES in self.options.enable_incomplete_feature
) and typ.type.fullname == "builtins.tuple"
if op in ("==", "is"):
# TODO: return fixed union + prefixed variadic tuple for no_type?
return TupleType(items=[arg] * size, fallback=typ), typ
elif op in ("<", "<="):
if op == "<=":
size += 1
if allow_precise:
unpack = UnpackType(self.named_generic_type("builtins.tuple", [arg]))
no_type: Type | None = TupleType(items=[arg] * size + [unpack], fallback=typ)
else:
no_type = typ
if allow_precise:
items = []
for n in range(size):
items.append(TupleType([arg] * n, fallback=typ))
yes_type: Type | None = UnionType.make_union(items, typ.line, typ.column)
else:
yes_type = typ
return yes_type, no_type
else:
yes_type, no_type = self.refine_instance_type_with_len(typ, neg_ops[op], size)
return no_type, yes_type
#
# Helpers
#
@overload
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
code: ErrorCode | None = None,
outer_context: Context | None = None,
) -> bool: ...
@overload
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: ErrorMessage,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
outer_context: Context | None = None,
) -> bool: ...
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str | ErrorMessage,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
code: ErrorCode | None = None,
outer_context: Context | None = None,
) -> bool:
"""Generate an error if the subtype is not compatible with supertype."""
if is_subtype(subtype, supertype, options=self.options):
return True
if isinstance(msg, str):
msg = ErrorMessage(msg, code=code)
if self.msg.prefer_simple_messages():
self.fail(msg, context) # Fast path -- skip all fancy logic
return False
orig_subtype = subtype
subtype = get_proper_type(subtype)
orig_supertype = supertype
supertype = get_proper_type(supertype)
if self.msg.try_report_long_tuple_assignment_error(
subtype, supertype, context, msg, subtype_label, supertype_label
):
return False
extra_info: list[str] = []
note_msg = ""
notes = notes or []
if subtype_label is not None or supertype_label is not None:
subtype_str, supertype_str = format_type_distinctly(
orig_subtype, orig_supertype, options=self.options
)
if subtype_label is not None:
extra_info.append(subtype_label + " " + subtype_str)
if supertype_label is not None:
extra_info.append(supertype_label + " " + supertype_str)
note_msg = make_inferred_type_note(
outer_context or context, subtype, supertype, supertype_str
)
if isinstance(subtype, Instance) and isinstance(supertype, Instance):
notes = append_invariance_notes(notes, subtype, supertype)
if isinstance(subtype, UnionType) and isinstance(supertype, UnionType):
notes = append_union_note(notes, subtype, supertype, self.options)
if extra_info:
msg = msg.with_additional_msg(" (" + ", ".join(extra_info) + ")")
error = self.fail(msg, context)
for note in notes:
self.msg.note(note, context, code=msg.code)
if note_msg:
self.note(note_msg, context, code=msg.code)
self.msg.maybe_note_concatenate_pos_args(subtype, supertype, context, code=msg.code)
if (
isinstance(supertype, Instance)
and supertype.type.is_protocol
and isinstance(subtype, (CallableType, Instance, TupleType, TypedDictType, TypeType))
):
self.msg.report_protocol_problems(subtype, supertype, context, parent_error=error)
if isinstance(supertype, CallableType) and isinstance(subtype, Instance):
call = find_member("__call__", subtype, subtype, is_operator=True)
if call:
self.msg.note_call(subtype, call, context, code=msg.code)
if isinstance(subtype, (CallableType, Overloaded)) and isinstance(supertype, Instance):
if supertype.type.is_protocol and "__call__" in supertype.type.protocol_members:
call = find_member("__call__", supertype, subtype, is_operator=True)
assert call is not None
if not is_subtype(subtype, call, options=self.options):
self.msg.note_call(supertype, call, context, code=msg.code)
self.check_possible_missing_await(subtype, supertype, context, code=msg.code)
return False
def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:
"""If type implements Awaitable[X] with non-Any X, return X.
In all other cases return None. This method must be called in context
of local_errors.
"""
if isinstance(get_proper_type(typ), PartialType):
# Partial types are special, ignore them here.
return None
try:
aw_type = self.expr_checker.check_awaitable_expr(
typ, Context(), "", ignore_binder=True
)
except KeyError:
# This is a hack to speed up tests by not including Awaitable in all typing stubs.
return None
if local_errors.has_new_errors():
return None
if isinstance(get_proper_type(aw_type), (AnyType, UnboundType)):
return None
return aw_type
@contextmanager
def checking_await_set(self) -> Iterator[None]:
self.checking_missing_await = True
try:
yield
finally:
self.checking_missing_await = False
def check_possible_missing_await(
self, subtype: Type, supertype: Type, context: Context, code: ErrorCode | None
) -> None:
"""Check if the given type becomes a subtype when awaited."""
if self.checking_missing_await:
# Avoid infinite recursion.
return
with self.checking_await_set(), self.msg.filter_errors() as local_errors:
aw_type = self.get_precise_awaitable_type(subtype, local_errors)
if aw_type is None:
return
if not self.check_subtype(
aw_type, supertype, context, msg=message_registry.INCOMPATIBLE_TYPES
):
return
self.msg.possible_missing_await(context, code)
def named_type(self, name: str) -> Instance:
"""Return an instance type with given name and implicit Any type args.
For example, named_type('builtins.object') produces the 'object' type.
"""
if name == "builtins.str":
if instance_cache.str_type is None:
instance_cache.str_type = self._named_type(name)
return instance_cache.str_type
if name == "builtins.function":
if instance_cache.function_type is None:
instance_cache.function_type = self._named_type(name)
return instance_cache.function_type
if name == "builtins.int":
if instance_cache.int_type is None:
instance_cache.int_type = self._named_type(name)
return instance_cache.int_type
if name == "builtins.bool":
if instance_cache.bool_type is None:
instance_cache.bool_type = self._named_type(name)
return instance_cache.bool_type
if name == "builtins.object":
if instance_cache.object_type is None:
instance_cache.object_type = self._named_type(name)
return instance_cache.object_type
return self._named_type(name)
def _named_type(self, name: str) -> Instance:
# Assume that the name refers to a type.
sym = self.lookup_qualified(name)
node = sym.node
if isinstance(node, TypeAlias):
assert isinstance(node.target, Instance) # type: ignore[misc]
node = node.target.type
assert isinstance(node, TypeInfo), node
any_type = AnyType(TypeOfAny.from_omitted_generics)
return Instance(node, [any_type] * len(node.defn.type_vars))
def named_generic_type(self, name: str, args: list[Type]) -> Instance:
"""Return an instance with the given name and type arguments.
Assume that the number of arguments is correct. Assume that
the name refers to a compatible generic type.
"""
info = self.lookup_typeinfo(name)
args = [remove_instance_last_known_values(arg) for arg in args]
# TODO: assert len(args) == len(info.defn.type_vars)
return Instance(info, args)
def lookup_typeinfo(self, fullname: str) -> TypeInfo:
# Assume that the name refers to a class.
sym = self.lookup_qualified(fullname)
node = sym.node
assert isinstance(node, TypeInfo), node
return node
def type_type(self) -> Instance:
"""Return instance type 'type'."""
return self.named_type("builtins.type")
def str_type(self) -> Instance:
"""Return instance type 'str'."""
return self.named_type("builtins.str")
def store_type(self, node: Expression, typ: Type) -> None:
"""Store the type of a node in the type map."""
self._type_maps[-1][node] = typ
def has_type(self, node: Expression) -> bool:
return any(node in m for m in reversed(self._type_maps))
def lookup_type_or_none(self, node: Expression) -> Type | None:
for m in reversed(self._type_maps):
if node in m:
return m[node]
return None
def lookup_type(self, node: Expression) -> Type:
for m in reversed(self._type_maps):
t = m.get(node)
if t is not None:
return t
raise KeyError(node)
def store_types(self, d: dict[Expression, Type]) -> None:
self._type_maps[-1].update(d)
def in_checked_function(self) -> bool:
"""Should we type-check the current function?
- Yes if --check-untyped-defs is set.
- Yes outside functions.
- Yes in annotated functions.
- No otherwise.
"""
return (
self.options.check_untyped_defs or not self.dynamic_funcs or not self.dynamic_funcs[-1]
)
def lookup(self, name: str) -> SymbolTableNode:
"""Look up a definition from the symbol table with the given name."""
if name in self.globals:
return self.globals[name]
else:
b = self.globals.get("__builtins__", None)
if b:
assert isinstance(b.node, MypyFile)
table = b.node.names
if name in table:
return table[name]
raise KeyError(f"Failed lookup: {name}")
def lookup_qualified(self, name: str) -> SymbolTableNode:
if "." not in name:
return self.lookup(name)
else:
parts = name.split(".")
n = self.modules[parts[0]]
for i in range(1, len(parts) - 1):
sym = n.names.get(parts[i])
assert sym is not None, "Internal error: attempted lookup of unknown name"
assert isinstance(sym.node, MypyFile)
n = sym.node
last = parts[-1]
if last in n.names:
return n.names[last]
elif len(parts) == 2 and parts[0] in ("builtins", "typing"):
fullname = ".".join(parts)
if fullname in SUGGESTED_TEST_FIXTURES:
suggestion = ", e.g. add '[{} fixtures/{}]' to your test".format(
parts[0], SUGGESTED_TEST_FIXTURES[fullname]
)
else:
suggestion = ""
raise KeyError(
"Could not find builtin symbol '{}' (If you are running a "
"test case, use a fixture that "
"defines this symbol{})".format(last, suggestion)
)
else:
msg = "Failed qualified lookup: '{}' (fullname = '{}')."
raise KeyError(msg.format(last, name))
@contextmanager
def enter_partial_types(
self, *, is_function: bool = False, is_class: bool = False
) -> Iterator[None]:
"""Enter a new scope for collecting partial types.
Also report errors for (some) variables which still have partial
types, i.e. we couldn't infer a complete type.
"""
is_local = (self.partial_types and self.partial_types[-1].is_local) or is_function
self.partial_types.append(PartialTypeScope({}, is_function, is_local))
yield
# Don't complain about not being able to infer partials if it is
# at the toplevel (with allow_untyped_globals) or if it is in an
# untyped function being checked with check_untyped_defs.
permissive = (self.options.allow_untyped_globals and not is_local) or (
self.options.check_untyped_defs and self.dynamic_funcs and self.dynamic_funcs[-1]
)
partial_types, _, _ = self.partial_types.pop()
if not self.current_node_deferred:
for var, context in partial_types.items():
# If we require local partial types, there are a few exceptions where
# we fall back to inferring just "None" as the type from a None initializer:
#
# 1. If all happens within a single function this is acceptable, since only
# the topmost function is a separate target in fine-grained incremental mode.
# We primarily want to avoid "splitting" partial types across targets.
#
# 2. A None initializer in the class body if the attribute is defined in a base
# class is fine, since the attribute is already defined and it's currently okay
# to vary the type of an attribute covariantly. The None type will still be
# checked for compatibility with base classes elsewhere. Without this exception
# mypy could require an annotation for an attribute that already has been
# declared in a base class, which would be bad.
allow_none = (
not self.options.local_partial_types
or is_function
or (is_class and self.is_defined_in_base_class(var))
)
if (
allow_none
and isinstance(var.type, PartialType)
and var.type.type is None
and not permissive
):
var.type = NoneType()
else:
if var not in self.partial_reported and not permissive:
self.msg.need_annotation_for_var(var, context, self.options)
self.partial_reported.add(var)
if var.type:
fixed = fixup_partial_type(var.type)
var.invalid_partial_type = fixed != var.type
var.type = fixed
def handle_partial_var_type(
self, typ: PartialType, is_lvalue: bool, node: Var, context: Context
) -> Type:
"""Handle a reference to a partial type through a var.
(Used by checkexpr and checkmember.)
"""
in_scope, is_local, partial_types = self.find_partial_types_in_all_scopes(node)
if typ.type is None and in_scope:
# 'None' partial type. It has a well-defined type. In an lvalue context
# we want to preserve the knowledge of it being a partial type.
if not is_lvalue:
return NoneType()
else:
return typ
else:
if partial_types is not None and not self.current_node_deferred:
if in_scope:
context = partial_types[node]
if is_local or not self.options.allow_untyped_globals:
self.msg.need_annotation_for_var(node, context, self.options)
self.partial_reported.add(node)
else:
# Defer the node -- we might get a better type in the outer scope
self.handle_cannot_determine_type(node.name, context)
return fixup_partial_type(typ)
def is_defined_in_base_class(self, var: Var) -> bool:
if not var.info:
return False
return var.info.fallback_to_any or any(
base.get(var.name) is not None for base in var.info.mro[1:]
)
def find_partial_types(self, var: Var) -> dict[Var, Context] | None:
"""Look for an active partial type scope containing variable.
A scope is active if assignments in the current context can refine a partial
type originally defined in the scope. This is affected by the local_partial_types
configuration option.
"""
in_scope, _, partial_types = self.find_partial_types_in_all_scopes(var)
if in_scope:
return partial_types
return None
def find_partial_types_in_all_scopes(
self, var: Var
) -> tuple[bool, bool, dict[Var, Context] | None]:
"""Look for partial type scope containing variable.
Return tuple (is the scope active, is the scope a local scope, scope).
"""
for scope in reversed(self.partial_types):
if var in scope.map:
# All scopes within the outermost function are active. Scopes out of
# the outermost function are inactive to allow local reasoning (important
# for fine-grained incremental mode).
disallow_other_scopes = self.options.local_partial_types
if isinstance(var.type, PartialType) and var.type.type is not None and var.info:
# This is an ugly hack to make partial generic self attributes behave
# as if --local-partial-types is always on (because it used to be like this).
disallow_other_scopes = True
scope_active = (
not disallow_other_scopes or scope.is_local == self.partial_types[-1].is_local
)
return scope_active, scope.is_local, scope.map
return False, False, None
def temp_node(self, t: Type, context: Context | None = None) -> TempNode:
"""Create a temporary node with the given, fixed type."""
return TempNode(t, context=context)
def fail(
self, msg: str | ErrorMessage, context: Context, *, code: ErrorCode | None = None
) -> ErrorInfo:
"""Produce an error message."""
if isinstance(msg, ErrorMessage):
return self.msg.fail(msg.value, context, code=msg.code)
return self.msg.fail(msg, context, code=code)
def note(
self,
msg: str | ErrorMessage,
context: Context,
offset: int = 0,
*,
code: ErrorCode | None = None,
) -> None:
"""Produce a note."""
if isinstance(msg, ErrorMessage):
self.msg.note(msg.value, context, code=msg.code)
return
self.msg.note(msg, context, offset=offset, code=code)
def iterable_item_type(
self, it: Instance | CallableType | TypeType | Overloaded, context: Context
) -> Type:
if isinstance(it, Instance):
iterable = map_instance_to_supertype(it, self.lookup_typeinfo("typing.Iterable"))
item_type = iterable.args[0]
if not isinstance(get_proper_type(item_type), AnyType):
# This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'
# in case there is no explicit base class.
return item_type
# Try also structural typing.
return self.analyze_iterable_item_type_without_expression(it, context)[1]
def function_type(self, func: FuncBase) -> FunctionLike:
return function_type(func, self.named_type("builtins.function"))
def push_type_map(self, type_map: TypeMap, *, from_assignment: bool = True) -> None:
if type_map is None:
self.binder.unreachable()
else:
for expr, type in type_map.items():
self.binder.put(expr, type, from_assignment=from_assignment)
def infer_issubclass_maps(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]:
"""Infer type restrictions for an expression in issubclass call."""
vartype = self.lookup_type(expr)
type = self.get_isinstance_type(node.args[1])
if isinstance(vartype, TypeVarType):
vartype = vartype.upper_bound
vartype = get_proper_type(vartype)
if isinstance(vartype, UnionType):
union_list = []
for t in get_proper_types(vartype.items):
if isinstance(t, TypeType):
union_list.append(t.item)
else:
# This is an error that should be reported earlier
# if we reach here, we refuse to do any type inference.
return {}, {}
vartype = UnionType(union_list)
elif isinstance(vartype, TypeType):
vartype = vartype.item
elif isinstance(vartype, Instance) and vartype.type.is_metaclass():
vartype = self.named_type("builtins.object")
else:
# Any other object whose type we don't know precisely
# for example, Any or a custom metaclass.
return {}, {} # unknown type
yes_type, no_type = self.conditional_types_with_intersection(vartype, type, expr)
yes_map, no_map = conditional_types_to_typemaps(expr, yes_type, no_type)
yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))
return yes_map, no_map
@overload
def conditional_types_with_intersection(
self,
expr_type: Type,
type_ranges: list[TypeRange] | None,
ctx: Context,
default: None = None,
*,
consider_runtime_isinstance: bool = True,
) -> tuple[Type | None, Type | None]: ...
@overload
def conditional_types_with_intersection(
self,
expr_type: Type,
type_ranges: list[TypeRange] | None,
ctx: Context,
default: Type,
*,
consider_runtime_isinstance: bool = True,
) -> tuple[Type, Type]: ...
def conditional_types_with_intersection(
self,
expr_type: Type,
type_ranges: list[TypeRange] | None,
ctx: Context,
default: Type | None = None,
*,
consider_runtime_isinstance: bool = True,
) -> tuple[Type | None, Type | None]:
initial_types = conditional_types(
expr_type,
type_ranges,
default,
consider_runtime_isinstance=consider_runtime_isinstance,
)
# For some reason, doing "yes_map, no_map = conditional_types_to_typemaps(...)"
# doesn't work: mypyc will decide that 'yes_map' is of type None if we try.
yes_type: Type | None = initial_types[0]
no_type: Type | None = initial_types[1]
if not isinstance(get_proper_type(yes_type), UninhabitedType) or type_ranges is None:
return yes_type, no_type
# If conditional_types was unable to successfully narrow the expr_type
# using the type_ranges and concluded if-branch is unreachable, we try
# computing it again using a different algorithm that tries to generate
# an ad-hoc intersection between the expr_type and the type_ranges.
proper_type = get_proper_type(expr_type)
if isinstance(proper_type, UnionType):
possible_expr_types = get_proper_types(proper_type.relevant_items())
else:
possible_expr_types = [proper_type]
possible_target_types = []
for tr in type_ranges:
item = get_proper_type(tr.item)
if isinstance(item, (Instance, NoneType)):
possible_target_types.append(item)
if not possible_target_types:
return yes_type, no_type
out = []
errors: list[tuple[str, str]] = []
for v in possible_expr_types:
if not isinstance(v, Instance):
return yes_type, no_type
for t in possible_target_types:
if isinstance(t, NoneType):
errors.append((f'"{v.type.name}" and "NoneType"', '"NoneType" is final'))
continue
intersection = self.intersect_instances((v, t), errors)
if intersection is None:
continue
out.append(intersection)
if not out:
# Only report errors if no element in the union worked.
if self.should_report_unreachable_issues():
for types, reason in errors:
self.msg.impossible_intersection(types, reason, ctx)
return UninhabitedType(), expr_type
new_yes_type = make_simplified_union(out)
return new_yes_type, expr_type
def is_writable_attribute(self, node: Node) -> bool:
"""Check if an attribute is writable"""
if isinstance(node, Var):
if node.is_property and not node.is_settable_property:
return False
return True
elif isinstance(node, OverloadedFuncDef) and node.is_property:
first_item = node.items[0]
assert isinstance(first_item, Decorator)
return first_item.var.is_settable_property
return False
def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
"""Get the type(s) resulting from an isinstance check.
Returns an empty list for isinstance(x, ()).
"""
if isinstance(expr, OpExpr) and expr.op == "|":
left = self.get_isinstance_type(expr.left)
if left is None and is_literal_none(expr.left):
left = [TypeRange(NoneType(), is_upper_bound=False)]
right = self.get_isinstance_type(expr.right)
if right is None and is_literal_none(expr.right):
right = [TypeRange(NoneType(), is_upper_bound=False)]
if left is None or right is None:
return None
return left + right
all_types = get_proper_types(flatten_types(self.lookup_type(expr)))
types: list[TypeRange] = []
for typ in all_types:
if isinstance(typ, FunctionLike) and typ.is_type_obj():
# If a type is generic, `isinstance` can only narrow its variables to Any.
any_parameterized = fill_typevars_with_any(typ.type_object())
# Tuples may have unattended type variables among their items
if isinstance(any_parameterized, TupleType):
erased_type = erase_typevars(any_parameterized)
else:
erased_type = any_parameterized
types.append(TypeRange(erased_type, is_upper_bound=False))
elif isinstance(typ, TypeType):
# Type[A] means "any type that is a subtype of A" rather than "precisely type A"
# we indicate this by setting is_upper_bound flag
is_upper_bound = True
if isinstance(typ.item, NoneType):
# except for Type[None], because "'NoneType' is not an acceptable base type"
is_upper_bound = False
types.append(TypeRange(typ.item, is_upper_bound=is_upper_bound))
elif isinstance(typ, Instance) and typ.type.fullname == "builtins.type":
object_type = Instance(typ.type.mro[-1], [])
types.append(TypeRange(object_type, is_upper_bound=True))
elif isinstance(typ, Instance) and typ.type.fullname == "types.UnionType" and typ.args:
types.append(TypeRange(UnionType(typ.args), is_upper_bound=False))
elif isinstance(typ, AnyType):
types.append(TypeRange(typ, is_upper_bound=False))
else: # we didn't see an actual type, but rather a variable with unknown value
return None
return types
def is_literal_enum(self, n: Expression) -> bool:
"""Returns true if this expression (with the given type context) is an Enum literal.
For example, if we had an enum:
class Foo(Enum):
A = 1
B = 2
...and if the expression 'Foo' referred to that enum within the current type context,
then the expression 'Foo.A' would be a literal enum. However, if we did 'a = Foo.A',
then the variable 'a' would *not* be a literal enum.
We occasionally special-case expressions like 'Foo.A' and treat them as a single primitive
unit for the same reasons we sometimes treat 'True', 'False', or 'None' as a single
primitive unit.
"""
if not isinstance(n, MemberExpr) or not isinstance(n.expr, NameExpr):
return False
parent_type = self.lookup_type_or_none(n.expr)
member_type = self.lookup_type_or_none(n)
if member_type is None or parent_type is None:
return False
parent_type = get_proper_type(parent_type)
member_type = get_proper_type(coerce_to_literal(member_type))
if not isinstance(parent_type, FunctionLike) or not isinstance(member_type, LiteralType):
return False
if not parent_type.is_type_obj():
return False
return (
member_type.is_enum_literal()
and member_type.fallback.type == parent_type.type_object()
)
def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:
"""Inject an extra attribute with Any type using fallbacks."""
orig_typ = typ
typ = get_proper_type(typ)
any_type = AnyType(TypeOfAny.unannotated)
if isinstance(typ, Instance):
result = typ.copy_with_extra_attr(name, any_type)
# For instances, we erase the possible module name, so that restrictions
# become anonymous types.ModuleType instances, allowing hasattr() to
# have effect on modules.
assert result.extra_attrs is not None
result.extra_attrs.mod_name = None
return result
if isinstance(typ, TupleType):
fallback = typ.partial_fallback.copy_with_extra_attr(name, any_type)
return typ.copy_modified(fallback=fallback)
if isinstance(typ, CallableType):
fallback = typ.fallback.copy_with_extra_attr(name, any_type)
return typ.copy_modified(fallback=fallback)
if isinstance(typ, TypeType) and isinstance(typ.item, Instance):
return TypeType.make_normalized(
self.add_any_attribute_to_type(typ.item, name), is_type_form=typ.is_type_form
)
if isinstance(typ, TypeVarType):
return typ.copy_modified(
upper_bound=self.add_any_attribute_to_type(typ.upper_bound, name),
values=[self.add_any_attribute_to_type(v, name) for v in typ.values],
)
if isinstance(typ, UnionType):
with_attr, without_attr = self.partition_union_by_attr(typ, name)
return make_simplified_union(
with_attr + [self.add_any_attribute_to_type(typ, name) for typ in without_attr]
)
return orig_typ
def hasattr_type_maps(
self, expr: Expression, source_type: Type, name: str
) -> tuple[TypeMap, TypeMap]:
"""Simple support for hasattr() checks.
Essentially the logic is following:
* In the if branch, keep types that already has a valid attribute as is,
for other inject an attribute with `Any` type.
* In the else branch, remove types that already have a valid attribute,
while keeping the rest.
"""
if self.has_valid_attribute(source_type, name):
return {expr: source_type}, {}
source_type = get_proper_type(source_type)
if isinstance(source_type, UnionType):
_, without_attr = self.partition_union_by_attr(source_type, name)
yes_map = {expr: self.add_any_attribute_to_type(source_type, name)}
return yes_map, {expr: make_simplified_union(without_attr)}
type_with_attr = self.add_any_attribute_to_type(source_type, name)
if type_with_attr != source_type:
return {expr: type_with_attr}, {}
return {}, {}
def partition_union_by_attr(
self, source_type: UnionType, name: str
) -> tuple[list[Type], list[Type]]:
with_attr = []
without_attr = []
for item in source_type.items:
if self.has_valid_attribute(item, name):
with_attr.append(item)
else:
without_attr.append(item)
return with_attr, without_attr
def has_valid_attribute(self, typ: Type, name: str) -> bool:
p_typ = get_proper_type(typ)
if isinstance(p_typ, AnyType):
return False
if isinstance(p_typ, Instance) and p_typ.extra_attrs and p_typ.extra_attrs.mod_name:
# Presence of module_symbol_table means this check will skip ModuleType.__getattr__
module_symbol_table = p_typ.type.names
else:
module_symbol_table = None
with self.msg.filter_errors() as watcher:
analyze_member_access(
name,
typ,
TempNode(AnyType(TypeOfAny.special_form)),
is_lvalue=False,
is_super=False,
is_operator=False,
original_type=typ,
chk=self,
# This is not a real attribute lookup so don't mess with deferring nodes.
no_deferral=True,
module_symbol_table=module_symbol_table,
)
return not watcher.has_new_errors()
def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type:
return self.expr_checker.accept(node, type_context=type_context)
def is_defined_in_stub(self, typ: Instance, /) -> bool:
return self.modules[typ.type.module_name].is_stub
def check_deprecated(self, node: Node | None, context: Context) -> None:
"""Warn if deprecated and not directly imported with a `from` statement."""
if isinstance(node, Decorator):
node = node.func
if isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo)) and (
node.deprecated is not None
):
for imp in self.tree.imports:
if isinstance(imp, ImportFrom) and any(node.name == n[0] for n in imp.names):
break
else:
self.warn_deprecated(node, context)
def warn_deprecated(self, node: Node | None, context: Context) -> None:
"""Warn if deprecated."""
if isinstance(node, Decorator):
node = node.func
if (
isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo))
and (deprecated := node.deprecated) is not None
and not self.is_typeshed_stub
and not any(
node.fullname == p or node.fullname.startswith(f"{p}.")
for p in self.options.deprecated_calls_exclude
)
):
warn = self.msg.note if self.options.report_deprecated_as_note else self.msg.fail
warn(deprecated, context, code=codes.DEPRECATED)
def new_unique_dummy_name(self, namespace: str) -> str:
"""Generate a name that is guaranteed to be unique for this TypeChecker instance."""
name = f"dummy-{namespace}-{self._unique_id}"
self._unique_id += 1
return name
# leafs
def visit_pass_stmt(self, o: PassStmt, /) -> None:
return None
def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None:
return None
def visit_global_decl(self, o: GlobalDecl, /) -> None:
return None
| TypeChecker |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/factory.py | {
"start": 2373,
"end": 2530
} | class ____(NamedTuple):
requirements: list[Requirement]
constraints: dict[str, Constraint]
user_requested: dict[str, int]
| CollectedRootRequirements |
python | huggingface__transformers | src/transformers/models/got_ocr2/modular_got_ocr2.py | {
"start": 5615,
"end": 9348
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GotOcr2ForConditionalGeneration`]. It is used to instantiate a
GotOcr2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of GOT-OCR-2.0.
e.g [stepfun-ai/GOT-OCR-2.0-hf](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
The config object or dictionary of the vision backbone.
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
The config object or dictionary of the text backbone.
image_token_index (`int`, *optional*, defaults to 151859):
The image token index to encode the image prompt.
image_seq_length (`int`, *optional*, defaults to 576):
Sequence length of one image embedding.
pad_token_id (`int`, *optional*, defaults to -1):
Padding token id.
```python
>>> from transformers import GotOcr2ForConditionalGeneration, GotOcr2Config
>>> # Initializing a GotOcr2 style configuration
>>> configuration = GotOcr2Config()
>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = GotOcr2ForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "got_ocr2"
attribute_map = {
"image_token_id": "image_token_index",
}
sub_configs = {"text_config": AutoConfig, "vision_config": GotOcr2VisionConfig}
def __init__(
self,
vision_config: Optional[dict] = None,
text_config: Optional[dict] = None,
image_token_index: Optional[int] = 151859,
image_seq_length: Optional[int] = 576,
pad_token_id: Optional[int] = -1,
**kwargs,
):
self.image_token_index = image_token_index
self.image_seq_length = image_seq_length
self.pad_token_id = pad_token_id
if vision_config is None:
self.vision_config = GotOcr2VisionConfig()
elif isinstance(vision_config, dict):
self.vision_config = GotOcr2VisionConfig(**vision_config)
elif isinstance(vision_config, GotOcr2VisionConfig):
self.vision_config = vision_config
if isinstance(text_config, dict):
text_config["model_type"] = text_config.get("model_type", "qwen2")
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
elif text_config is None:
text_config = CONFIG_MAPPING["qwen2"](
vocab_size=151860,
hidden_size=1024,
intermediate_size=2816,
num_hidden_layers=24,
num_attention_heads=16,
num_key_value_heads=16,
hidden_act="silu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=True,
rope_theta=1000000.0,
rope_parameters=None,
use_sliding_window=False,
sliding_window=4096,
max_window_layers=21,
attention_dropout=0.0,
)
self.text_config = text_config
super().__init__(**kwargs)
| GotOcr2Config |
python | google__jax | tests/pallas/indexing_test.py | {
"start": 9417,
"end": 24680
} | class ____(PallasBaseTest):
def test_multi_indexing_interpreter_only(self):
if not self.INTERPRET:
self.skipTest("Only supported in interpret mode")
# Interpret only test! YMMV actually compiling this.
def permute(left, right, left_out_ref, right_out_ref):
left_out = jnp.zeros_like(left)
left_out = left_out.at[:, 0].set(left[:, 0])
left_out = left_out.at[:, 1].set(right[:, 0])
left_out = left_out.at[:, 2:].set(left[:, 1:-1])
right_out = jnp.zeros_like(right)
right_out = right_out.at[:, :-1].set(right[:, 1:])
right_out = right_out.at[:, -1].set(left[:, -1])
left_out_ref[...] = left_out
right_out_ref[...] = right_out
def invoke_permutes(x_ref, y_ref, x_out_ref, y_out_ref):
shape = x_ref.shape
_, n = shape[-2], shape[-1]
x_ref = x_ref.at[: n // 2, : n // 2]
y_ref = y_ref.at[: n // 2, : n // 2]
x_out_ref = x_out_ref.at[: n // 2, : n // 2]
y_out_ref = y_out_ref.at[: n // 2, : n // 2]
permute(x_ref, y_ref, x_out_ref, y_out_ref)
n = 8
x = jnp.ones([n, n])
y = jnp.ones([n, n])
jitted_permute = jax.jit(invoke_permutes)
grid = (1,)
pl.pallas_call(
jitted_permute,
grid=grid,
out_shape=[
jax.ShapeDtypeStruct(x.shape, x.dtype),
jax.ShapeDtypeStruct(x.shape, y.dtype),
],
in_specs=[
pl.BlockSpec(x.shape, lambda i: (0, 0)),
pl.BlockSpec(y.shape, lambda i: (0, 0)),
],
out_specs=[
pl.BlockSpec(x.shape, lambda i: (0, 0)),
pl.BlockSpec(y.shape, lambda i: (0, 0)),
],
interpret=True,
)(x, y)
def test_multi_indexing_destination_ref(self):
if not self.INTERPRET:
self.skipTest("Only supported in interpret mode")
def kernel(x_ref, o_ref):
o_ref[...] = jnp.zeros_like(o_ref)
new_o_ref = o_ref.at[pl.ds(0, 8)].at[0].at[pl.ds(0, 4), pl.ds(0, 4)]
new_o_ref[...] = x_ref[...]
x = jax.random.normal(jax.random.key(0), shape=(4, 4))
result = pl.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((16, 16, 16), x.dtype),
interpret=True,
)(x)
expected = jnp.zeros((16, 16, 16)).at[0, 0:4, 0:4].set(x)
np.testing.assert_array_equal(result, expected)
def test_ellipsis_indexing_iterpret_only(self):
if not self.INTERPRET:
self.skipTest("Only supported in interpret mode")
# Interpret only test! YMMV actually compiling this.
def permute_columns_in_row_kernel(left, right, new_left, new_right):
shape = left.shape
k = shape[-1]
ndim = len(shape)
left_slices = [
left[..., :1],
right[..., :1],
left[..., 1:k-1]
]
right_slices = [
right[..., 1:k],
left[..., k-1:k]
]
new_left[...] = np.concatenate(left_slices, axis=ndim - 1)
new_right[...] = np.concatenate(right_slices, axis=ndim - 1)
left = jnp.array([[1, 2, 3], [4, 5, 6]], dtype=jnp.float32)
right = jnp.array([[7, 8, 9], [10, 11, 12]], dtype=jnp.float32)
output_shape = left.shape
# hack to reuse the same fn for np cat
import jax.numpy as np # noqa: F811
left_out, right_out = pl.pallas_call(
permute_columns_in_row_kernel,
grid=(1,),
out_shape=[
jax.ShapeDtypeStruct(output_shape, jnp.float32),
jax.ShapeDtypeStruct(output_shape, jnp.float32)
],
in_specs=[
pl.BlockSpec(left.shape, lambda i: (0, 0)),
pl.BlockSpec(right.shape, lambda i: (0, 0))
],
out_specs=[
pl.BlockSpec(output_shape, lambda i: (0, 0)),
pl.BlockSpec(output_shape, lambda i: (0, 0))
],
interpret=True,
)(left, right)
import numpy as np # noqa: F811
left_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
right_np = np.array([[7, 8, 9], [10, 11, 12]], dtype=np.float32)
left_out_np = left_np.copy()
right_out_np = right_np.copy()
permute_columns_in_row_kernel(left_np, right_np, left_out_np, right_out_np)
np.testing.assert_array_equal(left_out_np, left_out)
np.testing.assert_array_equal(right_out_np, right_out)
@hp.given(hps.data())
def test_vmap_nd_indexing(self, data):
self.skipTest("TODO(necula): enable this test; was in jax_triton.")
vmap_shape = data.draw(hnp.array_shapes(min_dims=1, max_dims=3, min_side=2),
label="vmap_shape")
el_shape = data.draw(hnp.array_shapes(min_dims=2), label="el_shape")
# TODO(sharadmv,apaszke): enable rank 0 and rank 1 Refs
# hp.assume(len(el_shape) >= 2)
nd_indexer = NDIndexer.from_indices_shape(
data.draw(nd_indices_strategy(el_shape), label="nd_indexer"),
el_shape)
expected_shape = jax.eval_shape(lambda x: x[nd_indexer],
jax.ShapeDtypeStruct(el_shape, jnp.float32))
ref = lambda x: x[nd_indexer]
def kernel(x_ref, y_ref):
y_ref[...] = x_ref[nd_indexer]
func = pl.pallas_call(kernel, out_shape=expected_shape)
shape = el_shape
for vmap_dim in vmap_shape[::-1]:
index = data.draw(hps.integers(min_value=0,
max_value=max(0, len(shape) - 2)),
label="index")
# hp.assume(index <= max(0, len(shape) - 2))
# TODO(sharadmv,apaszke): enable vmapping over batch axes in 2 minormost
# dimensions
shape = (*shape[:index], vmap_dim, *shape[index:])
ref = jax.vmap(ref, in_axes=index, out_axes=0)
func = jax.vmap(func, in_axes=index, out_axes=0)
key = random.PRNGKey(0)
x = random.normal(key, shape, dtype=jnp.float32)
expected = ref(x)
y = func(x)
np.testing.assert_array_equal(y, expected)
@parameterized.product(case=_INDEXING_TEST_CASES)
def test_can_load_with_ref_at(self, case):
if self.INTERPRET:
self.skipTest("TODO: fails in interpret mode.")
in_shape, indexers, out_shape = case
dtype = jnp.float32
def body(x_ref, y_ref):
for indexer in indexers[:-1]:
x_ref = x_ref.at[indexer]
x = x_ref[indexers[-1]]
y_ref[...] = x
x = random.normal(random.key(0), in_shape, dtype=dtype)
y = x
for indexer in indexers:
if not isinstance(indexer, tuple):
indexer = (indexer,)
indexer = tuple(map(_maybe_ds_to_slice, indexer))
y = y[indexer]
assert y.shape == out_shape
out = self.pallas_call(body, out_shape=y)(x)
self.assertAllClose(out, y)
@parameterized.product(case=_INDEXING_TEST_CASES)
def test_can_store_with_ref_at(self, case):
if self.INTERPRET:
self.skipTest("TODO: fails in interpret mode.")
in_shape, indexers, val_shape = case
dtype = jnp.float32
def body(x_ref, y_ref):
y_ref[...] = jnp.zeros_like(y_ref)
for indexer in indexers[:-1]:
y_ref = y_ref.at[indexer]
x = x_ref[...]
y_ref[indexers[-1]] = x
val = random.normal(random.key(0), val_shape, dtype=dtype)
# Use NumPy arrays to do nested indexing and mutation. This is really
# annoying to do in vanilla JAX.
x = np.zeros(in_shape, dtype=dtype)
y = x
for indexer in indexers:
if not isinstance(indexer, tuple):
indexer = (indexer,)
indexer = tuple(map(_maybe_ds_to_slice, indexer))
y = y[indexer]
assert y.shape == val_shape
y[...] = val
out = self.pallas_call(body, out_shape=x)(val)
self.assertAllClose(out, x)
@parameterized.product(slice_type=["slice", "ds"])
@hp.given(
ref_shape=hps.sampled_from(((8, 8, 32), (7, 7, 33))),
indices=hps.tuples(
hps.integers(0, 6), hps.integers(0, 6), hps.integers(0, 31)
),
strides=hps.tuples(
hps.integers(1, 10), hps.integers(1, 10), hps.integers(1, 10)
),
)
def test_strided_load_and_store(
self, slice_type, ref_shape, indices, strides
):
if self.INTERPRET:
self.skipTest("TODO: fails in interpret mode.")
ref_shape = (*ref_shape, 128)
indices = (*indices, 0)
strides = (*strides, 1)
vec_shape = [
(l - i + s - 1) // s for l, i, s in zip(ref_shape, indices, strides)
]
dtype = jnp.float32
def body(x_ref, y_ref1, y_ref2):
if slice_type == "slice":
slices = tuple(
slice(i, rs, s) for i, rs, s in zip(indices, ref_shape, strides)
)
else:
slices = tuple(
pl.ds(i, vs, s) for i, vs, s in zip(indices, vec_shape, strides)
)
y_ref1[...] = x_ref[slices]
y_ref2[slices] = y_ref1[...]
x = random.normal(random.key(0), ref_shape, dtype=dtype)
y1, y2 = self.pallas_call(
body,
out_shape=[
jax.ShapeDtypeStruct(vec_shape, dtype),
jax.ShapeDtypeStruct(ref_shape, dtype),
],
)(x)
slices = tuple(
slice(i, l, s) for l, i, s in zip(ref_shape, indices, strides)
)
expected = x[slices]
self.assertAllClose(y1, expected, err_msg="Strided Load Error")
self.assertAllClose(
y2[slices], expected, err_msg="Strided Store Error"
)
@hp.given(hps.data())
def test_load_and_broadcast_with_stride_0(self, data):
if not jtu.if_cloud_tpu_at_least(2025, 11, 25):
self.skipTest("Requires libtpu built after 2025-11-25")
if self.INTERPRET:
self.skipTest("TODO: fails in interpret mode.")
dtype = jnp.float32
rank = data.draw(hps.integers(min_value=2, max_value=4))
shape = data.draw(hps.tuples(
*(hps.integers(min_value=1, max_value=10) for _ in range(rank - 1))))
shape = (*shape, 128)
strides = data.draw(hps.tuples(
*(hps.sampled_from([0, 1]) for _ in range(rank - 1))))
strides = (*strides, 1)
indices = []
for i in range(rank):
index = (data.draw(hps.integers(min_value=0, max_value=shape[i] - 1))
if strides[i] == 0 else 0)
indices.append(index)
def body(x_ref, y_ref):
slices = tuple(
pl.ds(i, l, s) for i, l, s in zip(indices, shape, strides)
)
y_ref[...] = x_ref[slices]
x = random.normal(random.key(33), shape, dtype=dtype)
y = self.pallas_call(
body,
out_shape=jax.ShapeDtypeStruct(shape, dtype),
)(x)
slices = tuple(slice(i, l, 1) if s != 0 else slice(i, i + 1, 1)
for i, l, s in zip(indices, shape, strides))
expected = jnp.broadcast_to(x[slices], shape)
self.assertAllClose(y, expected)
def test_load_with_dynamic_2nd_minor_index(self):
if pltpu is None:
self.skipTest("No TPU module available.")
# We can take any dynamic index on the 2nd minor dimension as long as
# the minormost dimsize is vreg lane count.
m, n = 32, 128
k = 10
start = 2
def kernel(x_ref, indices, y_ref):
y_ref[...] = x_ref[pl.ds(indices[0], k)]
x = jnp.arange(m * n, dtype=jnp.int32).reshape((m, n))
indices = jnp.array([start])
res = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((k, n), jnp.int32),
grid_spec=pltpu.PrefetchScalarGridSpec(
num_scalar_prefetch=0,
in_specs=[
pl.BlockSpec(memory_space=pltpu.VMEM),
pl.BlockSpec(memory_space=pltpu.SMEM),
],
),
)(x, indices)
self.assertAllClose(res, x[start : start + k, :], atol=0., rtol=0.)
def test_store_with_dynamic_2nd_minor_index(self):
if pltpu is None:
self.skipTest("No TPU module available.")
# We can take any dynamic index on the 2nd minor dimension as long as
# the minormost dimsize is vreg lane count.
m, n = 10, 128
k = 32
start = 2
def kernel(x_ref, indices, y_ref):
y_ref[pl.ds(indices[0], m)] = x_ref[...]
x = jnp.arange(m * n, dtype=jnp.int32).reshape((m, n))
indices = jnp.array([start])
res = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((k, n), jnp.int32),
grid_spec=pltpu.PrefetchScalarGridSpec(
num_scalar_prefetch=0,
in_specs=[
pl.BlockSpec(memory_space=pltpu.VMEM),
pl.BlockSpec(memory_space=pltpu.SMEM),
],
),
)(x, indices)
self.assertAllClose(res[start : start + m, :], x, atol=0., rtol=0.)
def test_load_one_row_with_dynamic_2nd_minor_index(self):
if pltpu is None:
self.skipTest("No TPU module available.")
# This test triggers strided load. We can take any dynamic index on the
# 2nd minor dimension as long as we load one row on the 2nd minor dim.
b, m, n = 4, 16, 256
start = 3
def kernel(x_ref, indices, y_ref):
y_ref[...] = x_ref[:, pl.ds(indices[0], 1), :]
x = jnp.arange(b * m * n, dtype=jnp.int32).reshape((b, m, n))
indices = jnp.array([start])
res = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((b, 1, n), jnp.int32),
grid_spec=pltpu.PrefetchScalarGridSpec(
num_scalar_prefetch=0,
in_specs=[
pl.BlockSpec(memory_space=pltpu.VMEM),
pl.BlockSpec(memory_space=pltpu.SMEM),
],
),
)(x, indices)
self.assertAllClose(res, x[:, start : start + 1, :], atol=0., rtol=0.)
def test_store_one_row_with_dynamic_2nd_minor_index(self):
if pltpu is None:
self.skipTest("No TPU module available.")
# This test triggers strided store. We can take any dynamic index on the
# 2nd minor dimension as long as we store one row on the 2nd minor dim.
b, m, n = 4, 16, 256
start = 3
def kernel(x_ref, indices, y_ref):
y_ref[:, pl.ds(indices[0], 1), :] = x_ref[...]
x = jnp.arange(b * 1 * n, dtype=jnp.int32).reshape((b, 1, n))
indices = jnp.array([start])
res = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((b, m, n), jnp.int32),
grid_spec=pltpu.PrefetchScalarGridSpec(
num_scalar_prefetch=0,
in_specs=[
pl.BlockSpec(memory_space=pltpu.VMEM),
pl.BlockSpec(memory_space=pltpu.SMEM),
],
),
)(x, indices)
self.assertAllClose(res[:, start : start + 1, :], x, atol=0., rtol=0.)
def test_scalar_load_from_vmem(self):
if not jtu.is_device_tpu_at_least(4):
self.skipTest("Requires TPU v4 or later")
def kernel(x_ref, o_ref, sem_ref):
o_ref[...] = jnp.zeros_like(o_ref)
scalar_val = x_ref[1, 2]
# Use scalar_val in both async_copy and store.
o_ref[scalar_val] = jnp.ones_like(o_ref[0]) * scalar_val
desc = pltpu.make_async_copy(
o_ref.at[scalar_val],
o_ref.at[scalar_val + 1],
sem_ref,
)
desc.start()
desc.wait()
x = jnp.array([[1, 2, 3], [4, 5, 6]], dtype=jnp.int32)
res = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((8, 8, 128), jnp.int32),
grid=(1,),
scratch_shapes=[pltpu.SemaphoreType.DMA]
)(x)
expected = jnp.zeros_like(res)
expected = expected.at[6].set(jnp.ones((8, 128), jnp.int32) * 6)
expected = expected.at[7].set(jnp.ones((8, 128), jnp.int32) * 6)
self.assertArraysEqual(res, expected)
| IndexerOpsTest |
python | keras-team__keras | keras/src/layers/regularization/gaussian_noise_test.py | {
"start": 125,
"end": 1071
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_gaussian_noise_basics(self):
self.run_layer_test(
layers.GaussianNoise,
init_kwargs={
"stddev": 0.2,
},
input_shape=(2, 3),
call_kwargs={"training": True},
expected_output_shape=(2, 3),
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=1,
expected_num_losses=0,
supports_masking=True,
assert_built_after_instantiation=True,
)
def test_gaussian_noise_correctness(self):
inputs = np.ones((20, 500))
layer = layers.GaussianNoise(0.3, seed=1337)
outputs = layer(inputs, training=True)
self.assertAllClose(
np.std(backend.convert_to_numpy(outputs)), 0.3, atol=0.02
)
| GaussianNoiseTest |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/preparation/units_normalization.py | {
"start": 271,
"end": 2164
} | class ____(PreparationStep):
"""
Represents a step which performs units normalization on a collection of intermediate queries.
Unit normalization refers to the process of making sure all components of a query have the values on the same
scale.
For example, if you have 100 ms * 100 s the normalization will convert it to 100 ms * 100000 ms.
"""
def _get_normalized_intermediate_query(
self, intermediate_query: IntermediateQuery
) -> IntermediateQuery:
"""
Computes the unit normalized query from an IntermediateQuery using a units normalization visitor.
Returns:
If the unit metadata returned by the visitor has a unit, the transformed intermediate query will be returned
, otherwise the supplied intermediate query will be returned.
"""
# We compute the new normalized query by visiting and mutating the expression tree.
unit_metadata, normalized_query = UnitsNormalizationVisitor().visit(
intermediate_query.metrics_query.query
)
if isinstance(unit_metadata, WithUnit):
return replace(
intermediate_query,
metrics_query=intermediate_query.metrics_query.set_query(normalized_query),
unit_family=unit_metadata.unit_family,
unit=unit_metadata.reference_unit,
scaling_factor=unit_metadata.scaling_factor,
)
return intermediate_query
def run(self, intermediate_queries: list[IntermediateQuery]) -> list[IntermediateQuery]:
normalized_intermediate_queries = []
for intermediate_query in intermediate_queries:
normalized_intermediate_queries.append(
self._get_normalized_intermediate_query(intermediate_query)
)
return normalized_intermediate_queries
| UnitsNormalizationStep |
python | doocs__leetcode | solution/2200-2299/2295.Replace Elements in an Array/Solution.py | {
"start": 0,
"end": 252
} | class ____:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
d = {x: i for i, x in enumerate(nums)}
for x, y in operations:
nums[d[x]] = y
d[y] = d[x]
return nums
| Solution |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 22858,
"end": 22979
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Centos'
strategy_class = RedHatStrategy
| CentOSHostname |
python | spack__spack | lib/spack/spack/vendor/archspec/cpu/microarchitecture.py | {
"start": 16179,
"end": 16354
} | class ____(ArchspecError, ValueError):
"""Raised if a compiler version does not support optimization for a given
micro-architecture.
"""
| UnsupportedMicroarchitecture |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 2499,
"end": 5148
} | class ____(
mixins.NodeDetailMixin,
mixins.NodeCancelMixin,
mixins.NodeUndoMixin,
mixins.NodeReviveMixin,
nodes.View,
):
"""
Represents a user-interaction node within a flow
.. code-block:: python
class MyFlow(flow.Flow):
...
approve = (
flow.View(views.UpdateProcessView.as_view(fields=["approved"]))
.Annotation(
title=_("Approve"),
description=_("Supervisor approvement"),
summary_template=_("Message review required"),
result_template=_(
"Message was {{ process.approved|yesno:'Approved,Rejected' }}"
),
)
.Permission(auto_create=True)
.Next(this.check_approve)
)
...
"""
index_view_class = views.UserIndexTaskView
detail_view_class = views.DetailTaskView
cancel_view_class = views.CancelTaskView
undo_view_class = views.UndoTaskView
revive_view_class = views.ReviveTaskView
"""
Execute View
"""
@property
def view(self):
return this.resolve(self.flow_class.instance, self._view)
@property
def view_path(self):
return path(
f"<int:process_pk>/{self.name}/<int:task_pk>/execute/",
utils.wrap_view(self, self.view),
name="execute",
)
"""
Assign user to a task
"""
assign_view_class = views.AssignTaskView
@viewprop
def assign_view(self):
"""View for a task assign."""
if self.assign_view_class:
return self.assign_view_class.as_view()
@property
def assign_path(self):
if self.assign_view:
return path(
f"<int:process_pk>/{self.name}/<int:task_pk>/assign/",
utils.wrap_task_view(
self, self.assign_view, permission=self.can_assign
),
name="assign",
)
"""
Unassign
"""
unassign_view_class = views.UnassignTaskView
@viewprop
def unassign_view(self):
"""View for a task assign."""
if self.unassign_view_class:
return self.unassign_view_class.as_view()
@property
def unassign_path(self):
if self.unassign_view:
return path(
f"<int:process_pk>/{self.name}/<int:task_pk>/unassign/",
utils.wrap_task_view(
self, self.unassign_view, permission=self.can_unassign
),
name="unassign",
)
| View |
python | jina-ai__jina | jina/serve/runtimes/monitoring.py | {
"start": 319,
"end": 1057
} | class ____:
"""The Monitoring Mixin for pods"""
def _setup_monitoring(self, monitoring: bool, port_monitoring: Union[int, str]):
"""
Wait for the monitoring server to start
:param monitoring: flag indicating whether monitoring has to be activated
:param port_monitoring: port where to expose the monitoring
"""
if monitoring:
from prometheus_client import CollectorRegistry
self.metrics_registry = CollectorRegistry()
else:
self.metrics_registry = None
if monitoring:
from prometheus_client import start_http_server
start_http_server(int(port_monitoring), registry=self.metrics_registry)
| MonitoringMixin |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_dataspec.py | {
"start": 17225,
"end": 17804
} | class ____:
def test_strict_key_values(self) -> None:
class FooSpatialUnits(HasProps):
x = bcpd.DistanceSpec("x")
f = FooSpatialUnits()
f.x = dict(field="foo", units="screen")
with pytest.raises(ValueError):
f.x = dict(field="foo", units="junk", foo="crap")
class FooAngleUnits(HasProps):
x = bcpd.AngleSpec("x")
f = FooAngleUnits()
f.x = dict(field="foo", units="deg")
with pytest.raises(ValueError):
f.x = dict(field="foo", units="junk", foo="crap")
| Test_UnitSpec |
python | pennersr__django-allauth | allauth/socialaccount/providers/okta/views.py | {
"start": 228,
"end": 1687
} | class ____(OAuth2Adapter):
provider_id = "okta"
settings = app_settings.PROVIDERS.get(provider_id, {})
okta_base_url = settings.get("OKTA_BASE_URL")
@property
def access_token_url(self):
return "https://{}/oauth2/v1/token".format(self.okta_base_url)
@property
def authorize_url(self):
return "https://{}/oauth2/v1/authorize".format(self.okta_base_url)
@property
def userinfo_url(self):
return "https://{}/oauth2/v1/userinfo".format(self.okta_base_url)
@property
def access_token_method(self):
return "POST"
def complete_login(self, request, app, token, **kwargs):
"""
Get the user info from userinfo endpoint and return a
A populated instance of the `SocialLogin` model (unsaved)
:param request:
:param app:
:param token:
:param kwargs:
:return:
"""
resp = (
get_adapter()
.get_requests_session()
.get(
self.userinfo_url,
headers={"Authorization": "Bearer {}".format(token.token)},
)
)
resp.raise_for_status()
extra_data = resp.json()
login = self.get_provider().sociallogin_from_response(request, extra_data)
return login
oauth2_login = OAuth2LoginView.adapter_view(OktaOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(OktaOAuth2Adapter)
| OktaOAuth2Adapter |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 130375,
"end": 131793
} | class ____(BaseTestCase, TraceItemTestCase):
def create_profile_function(
self,
organization: Organization | None = None,
project: Project | None = None,
timestamp: datetime | None = None,
trace_id: str | None = None,
attributes: dict[str, Any] | None = None,
) -> TraceItem:
if organization is None:
organization = self.organization
assert organization is not None
if project is None:
project = self.project
assert project is not None
if timestamp is None:
timestamp = datetime.now() - timedelta(minutes=1)
assert timestamp is not None
timestamp_proto = Timestamp()
timestamp_proto.FromDatetime(timestamp)
item_id = self.random_item_id()
attributes_proto = {}
if attributes:
for k, v in attributes.items():
attributes_proto[k] = scalar_to_any_value(v)
return TraceItem(
organization_id=organization.id,
project_id=project.id,
item_type=TraceItemType.TRACE_ITEM_TYPE_PROFILE_FUNCTION,
timestamp=timestamp_proto,
trace_id=trace_id or uuid4().hex,
item_id=item_id.bytes,
received=timestamp_proto,
retention_days=90,
attributes=attributes_proto,
)
| ProfileFunctionsTestCase |
python | SmileyChris__easy-thumbnails | demoproject/mainapp/migrations/0001_initial.py | {
"start": 123,
"end": 849
} | class ____(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestImage",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=100)),
(
"image",
easy_thumbnails.fields.ThumbnailerImageField(upload_to="images"),
),
],
),
]
| Migration |
python | pydantic__pydantic | .github/actions/people/people.py | {
"start": 3711,
"end": 3843
} | class ____(BaseModel):
"""Container for discussion comment nodes."""
nodes: list[DiscussionsCommentsNode]
| DiscussionsComments |
python | spack__spack | lib/spack/spack/vendor/attr/validators.py | {
"start": 15953,
"end": 16793
} | class ____:
min_length = attrib()
def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``__repr__``.
"""
if len(value) < self.min_length:
raise ValueError(
"Length of '{name}' must be => {min}: {len}".format(
name=attr.name, min=self.min_length, len=len(value)
)
)
def __repr__(self):
return "<min_len validator for {min}>".format(min=self.min_length)
def min_len(length):
"""
A validator that raises `ValueError` if the initializer is called
with a string or iterable that is shorter than *length*.
:param int length: Minimum length of the string or iterable
.. versionadded:: 22.1.0
"""
return _MinLengthValidator(length)
| _MinLengthValidator |
python | keras-team__keras | keras/src/layers/rnn/simple_rnn.py | {
"start": 8520,
"end": 17527
} | class ____(RNN):
"""Fully-connected RNN where the output is to be fed back as the new input.
Args:
units: Positive integer, dimensionality of the output space.
activation: Activation function to use.
Default: hyperbolic tangent (`tanh`).
If you pass None, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias: Boolean, (default `True`), whether the layer uses
a bias vector.
kernel_initializer: Initializer for the `kernel` weights matrix,
used for the linear transformation of the inputs. Default:
`"glorot_uniform"`.
recurrent_initializer: Initializer for the `recurrent_kernel`
weights matrix, used for the linear transformation of the recurrent
state. Default: `"orthogonal"`.
bias_initializer: Initializer for the bias vector. Default: `"zeros"`.
kernel_regularizer: Regularizer function applied to the `kernel` weights
matrix. Default: `None`.
recurrent_regularizer: Regularizer function applied to the
`recurrent_kernel` weights matrix. Default: `None`.
bias_regularizer: Regularizer function applied to the bias vector.
Default: `None`.
activity_regularizer: Regularizer function applied to the output of the
layer (its "activation"). Default: `None`.
kernel_constraint: Constraint function applied to the `kernel` weights
matrix. Default: `None`.
recurrent_constraint: Constraint function applied to the
`recurrent_kernel` weights matrix. Default: `None`.
bias_constraint: Constraint function applied to the bias vector.
Default: `None`.
dropout: Float between 0 and 1.
Fraction of the units to drop for the linear transformation
of the inputs. Default: 0.
recurrent_dropout: Float between 0 and 1.
Fraction of the units to drop for the linear transformation of the
recurrent state. Default: 0.
return_sequences: Boolean. Whether to return the last output
in the output sequence, or the full sequence. Default: `False`.
return_state: Boolean. Whether to return the last state
in addition to the output. Default: `False`.
go_backwards: Boolean (default: `False`).
If `True`, process the input sequence backwards and return the
reversed sequence.
stateful: Boolean (default: `False`). If `True`, the last state
for each sample at index i in a batch will be used as the
initial state for the sample of index i in the following batch.
unroll: Boolean (default: `False`).
If `True`, the network will be unrolled,
else a symbolic loop will be used.
Unrolling can speed-up an RNN,
although it tends to be more memory-intensive.
Unrolling is only suitable for short sequences.
Call arguments:
sequence: A 3D tensor, with shape `[batch, timesteps, feature]`.
mask: Binary tensor of shape `[batch, timesteps]` indicating whether
a given timestep should be masked. An individual `True` entry
indicates that the corresponding timestep should be utilized,
while a `False` entry indicates that the corresponding timestep
should be ignored.
training: Python boolean indicating whether the layer should behave in
training mode or in inference mode.
This argument is passed to the cell when calling it.
This is only relevant if `dropout` or `recurrent_dropout` is used.
initial_state: List of initial state tensors to be passed to the first
call of the cell.
Example:
```python
inputs = np.random.random((32, 10, 8))
simple_rnn = keras.layers.SimpleRNN(4)
output = simple_rnn(inputs) # The output has shape `(32, 4)`.
simple_rnn = keras.layers.SimpleRNN(
4, return_sequences=True, return_state=True
)
# whole_sequence_output has shape `(32, 10, 4)`.
# final_state has shape `(32, 4)`.
whole_sequence_output, final_state = simple_rnn(inputs)
```
"""
def __init__(
self,
units,
activation="tanh",
use_bias=True,
kernel_initializer="glorot_uniform",
recurrent_initializer="orthogonal",
bias_initializer="zeros",
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.0,
recurrent_dropout=0.0,
return_sequences=False,
return_state=False,
go_backwards=False,
stateful=False,
unroll=False,
seed=None,
**kwargs,
):
cell = SimpleRNNCell(
units,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
recurrent_initializer=recurrent_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
recurrent_regularizer=recurrent_regularizer,
bias_regularizer=bias_regularizer,
kernel_constraint=kernel_constraint,
recurrent_constraint=recurrent_constraint,
bias_constraint=bias_constraint,
dropout=dropout,
recurrent_dropout=recurrent_dropout,
seed=seed,
dtype=kwargs.get("dtype", None),
trainable=kwargs.get("trainable", True),
name="simple_rnn_cell",
)
super().__init__(
cell,
return_sequences=return_sequences,
return_state=return_state,
go_backwards=go_backwards,
stateful=stateful,
unroll=unroll,
**kwargs,
)
self.input_spec = [InputSpec(ndim=3)]
def call(self, sequences, initial_state=None, mask=None, training=False):
return super().call(
sequences, mask=mask, training=training, initial_state=initial_state
)
@property
def units(self):
return self.cell.units
@property
def activation(self):
return self.cell.activation
@property
def use_bias(self):
return self.cell.use_bias
@property
def kernel_initializer(self):
return self.cell.kernel_initializer
@property
def recurrent_initializer(self):
return self.cell.recurrent_initializer
@property
def bias_initializer(self):
return self.cell.bias_initializer
@property
def kernel_regularizer(self):
return self.cell.kernel_regularizer
@property
def recurrent_regularizer(self):
return self.cell.recurrent_regularizer
@property
def bias_regularizer(self):
return self.cell.bias_regularizer
@property
def kernel_constraint(self):
return self.cell.kernel_constraint
@property
def recurrent_constraint(self):
return self.cell.recurrent_constraint
@property
def bias_constraint(self):
return self.cell.bias_constraint
@property
def dropout(self):
return self.cell.dropout
@property
def recurrent_dropout(self):
return self.cell.recurrent_dropout
def get_config(self):
config = {
"units": self.units,
"activation": activations.serialize(self.activation),
"use_bias": self.use_bias,
"kernel_initializer": initializers.serialize(
self.kernel_initializer
),
"recurrent_initializer": initializers.serialize(
self.recurrent_initializer
),
"bias_initializer": initializers.serialize(self.bias_initializer),
"kernel_regularizer": regularizers.serialize(
self.kernel_regularizer
),
"recurrent_regularizer": regularizers.serialize(
self.recurrent_regularizer
),
"bias_regularizer": regularizers.serialize(self.bias_regularizer),
"activity_regularizer": regularizers.serialize(
self.activity_regularizer
),
"kernel_constraint": constraints.serialize(self.kernel_constraint),
"recurrent_constraint": constraints.serialize(
self.recurrent_constraint
),
"bias_constraint": constraints.serialize(self.bias_constraint),
"dropout": self.dropout,
"recurrent_dropout": self.recurrent_dropout,
}
base_config = super().get_config()
del base_config["cell"]
return {**base_config, **config}
@classmethod
def from_config(cls, config):
return cls(**config)
| SimpleRNN |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/executors/ecs/test_ecs_executor.py | {
"start": 14788,
"end": 52951
} | class ____:
"""Tests the AWS ECS Executor."""
@mock.patch("airflow.providers.amazon.aws.executors.ecs.ecs_executor.AwsEcsExecutor.change_state")
def test_execute(self, change_state_mock, mock_airflow_key, mock_executor, mock_cmd):
"""Test execution from end-to-end."""
airflow_key = mock_airflow_key()
mock_executor.ecs.run_task.return_value = {
"tasks": [
{
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
}
],
"failures": [],
}
assert len(mock_executor.pending_tasks) == 0
mock_executor.execute_async(airflow_key, mock_cmd)
assert len(mock_executor.pending_tasks) == 1
mock_executor.attempt_task_runs()
mock_executor.ecs.run_task.assert_called_once()
# Task is stored in active worker.
assert len(mock_executor.active_workers) == 1
assert ARN1 in mock_executor.active_workers.task_by_key(airflow_key).task_arn
change_state_mock.assert_called_once_with(
airflow_key, TaskInstanceState.RUNNING, ARN1, remove_running=False
)
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Test requires Airflow 3+")
@mock.patch("airflow.providers.amazon.aws.executors.ecs.ecs_executor.AwsEcsExecutor.change_state")
def test_task_sdk(self, change_state_mock, mock_airflow_key, mock_executor, mock_cmd):
"""Test task sdk execution from end-to-end."""
from airflow.executors.workloads import ExecuteTask
workload = mock.Mock(spec=ExecuteTask)
workload.ti = mock.Mock(spec=TaskInstance)
workload.ti.key = mock_airflow_key()
tags_exec_config = [{"key": "FOO", "value": "BAR"}]
workload.ti.executor_config = {"tags": tags_exec_config}
ser_workload = json.dumps({"test_key": "test_value"})
workload.model_dump_json.return_value = ser_workload
mock_executor.queue_workload(workload, mock.Mock())
mock_executor.ecs.run_task.return_value = {
"tasks": [
{
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
}
],
"failures": [],
}
assert mock_executor.queued_tasks[workload.ti.key] == workload
assert len(mock_executor.pending_tasks) == 0
assert len(mock_executor.running) == 0
mock_executor._process_workloads([workload])
assert len(mock_executor.queued_tasks) == 0
assert len(mock_executor.running) == 1
assert workload.ti.key in mock_executor.running
assert len(mock_executor.pending_tasks) == 1
assert mock_executor.pending_tasks[0].command == [
"python",
"-m",
"airflow.sdk.execution_time.execute_workload",
"--json-string",
'{"test_key": "test_value"}',
]
mock_executor.attempt_task_runs()
mock_executor.ecs.run_task.assert_called_once()
assert len(mock_executor.pending_tasks) == 0
mock_executor.ecs.run_task.assert_called_once_with(
cluster="some-cluster",
count=1,
launchType="FARGATE",
platformVersion="LATEST",
taskDefinition="some-task-def",
tags=tags_exec_config,
networkConfiguration={
"awsvpcConfiguration": {
"assignPublicIp": "DISABLED",
"securityGroups": ["sg1", "sg2"],
"subnets": ["sub1", "sub2"],
},
},
overrides={
"containerOverrides": [
{
"command": [
"python",
"-m",
"airflow.sdk.execution_time.execute_workload",
"--json-string",
ser_workload,
],
"environment": [
{
"name": "AIRFLOW_IS_EXECUTOR_CONTAINER",
"value": "true",
},
],
"name": "container-name",
},
],
},
)
# Task is stored in active worker.
assert len(mock_executor.active_workers) == 1
assert ARN1 in mock_executor.active_workers.task_by_key(workload.ti.key).task_arn
change_state_mock.assert_called_once_with(
workload.ti.key, TaskInstanceState.RUNNING, ARN1, remove_running=False
)
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_success_execute_api_exception(self, mock_backoff, mock_executor, mock_cmd):
"""Test what happens when ECS throws an exception, but ultimately runs the task."""
run_task_exception = Exception("Test exception")
run_task_success = {
"tasks": [
{
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
}
],
"failures": [],
}
mock_executor.ecs.run_task.side_effect = [run_task_exception, run_task_exception, run_task_success]
mock_executor.execute_async(mock_airflow_key, mock_cmd)
expected_retry_count = 2
# Fail 2 times
for _ in range(expected_retry_count):
mock_executor.attempt_task_runs()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
# Pass in last attempt
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 0
assert ARN1 in mock_executor.active_workers.get_all_arns()
assert mock_backoff.call_count == expected_retry_count
for attempt_number in range(1, expected_retry_count):
mock_backoff.assert_has_calls([mock.call(attempt_number)])
def test_failed_execute_api_exception(self, mock_executor, mock_cmd):
"""Test what happens when ECS refuses to execute a task and throws an exception"""
mock_executor.ecs.run_task.side_effect = Exception("Test exception")
mock_executor.execute_async(mock_airflow_key, mock_cmd)
# No matter what, don't schedule until run_task becomes successful.
for _ in range(int(mock_executor.max_run_task_attempts) * 2):
mock_executor.attempt_task_runs()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
def test_failed_execute_api(self, mock_executor, mock_cmd):
"""Test what happens when ECS refuses to execute a task."""
mock_executor.ecs.run_task.return_value = {
"tasks": [],
"failures": [
{"arn": ARN1, "reason": "Sample Failure", "detail": "UnitTest Failure - Please ignore"}
],
}
mock_executor.execute_async(mock_airflow_key, mock_cmd)
# No matter what, don't schedule until run_task becomes successful.
for _ in range(int(mock_executor.max_run_task_attempts) * 2):
mock_executor.attempt_task_runs()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_attempt_task_runs_attempts_when_tasks_fail(self, _, mock_executor):
"""
Test case when all tasks fail to run.
The executor should attempt each task exactly once per sync() iteration.
It should preserve the order of tasks, and attempt each task up to
`max_run_task_attempts` times before dropping the task.
"""
airflow_keys = [
TaskInstanceKey("a", "task_a", "c", 1, -1),
TaskInstanceKey("a", "task_b", "c", 1, -1),
]
airflow_cmd1 = _generate_mock_cmd()
airflow_cmd2 = _generate_mock_cmd()
commands = [airflow_cmd1, airflow_cmd2]
failures = [Exception("Failure 1"), Exception("Failure 2")]
mock_executor.execute_async(airflow_keys[0], commands[0])
mock_executor.execute_async(airflow_keys[1], commands[1])
assert len(mock_executor.pending_tasks) == 2
assert len(mock_executor.active_workers.get_all_arns()) == 0
mock_executor.ecs.run_task.side_effect = failures
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
assert len(mock_executor.pending_tasks) == 2
assert len(mock_executor.active_workers.get_all_arns()) == 0
mock_executor.ecs.run_task.call_args_list.clear()
mock_executor.ecs.run_task.side_effect = failures
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
assert len(mock_executor.pending_tasks) == 2
assert len(mock_executor.active_workers.get_all_arns()) == 0
mock_executor.ecs.run_task.call_args_list.clear()
mock_executor.ecs.run_task.side_effect = failures
mock_executor.attempt_task_runs()
assert len(mock_executor.active_workers.get_all_arns()) == 0
assert len(mock_executor.pending_tasks) == 0
if airflow_version >= (2, 10, 0):
events = [(x.event, x.task_id, x.try_number) for x in mock_executor._task_event_logs]
assert events == [
("ecs task submit failure", "task_a", 1),
("ecs task submit failure", "task_b", 1),
]
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_attempt_task_runs_attempts_when_some_tasks_fal(self, _, mock_executor):
"""
Test case when one task fail to run, and a new task gets queued.
The executor should attempt each task exactly once per sync() iteration.
It should preserve the order of tasks, and attempt each task up to
`max_run_task_attempts` times before dropping the task. If a task succeeds, the task
should be removed from pending_jobs and into active_workers.
"""
airflow_keys = [
TaskInstanceKey("a", "task_a", "c", 1, -1),
TaskInstanceKey("a", "task_b", "c", 1, -1),
]
airflow_cmd1 = _generate_mock_cmd()
airflow_cmd2 = _generate_mock_cmd()
airflow_commands = [airflow_cmd1, airflow_cmd2]
task = {
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
}
success_response = {"tasks": [task], "failures": []}
responses = [Exception("Failure 1"), success_response]
mock_executor.execute_async(airflow_keys[0], airflow_commands[0])
mock_executor.execute_async(airflow_keys[1], airflow_commands[1])
assert len(mock_executor.pending_tasks) == 2
mock_executor.ecs.run_task.side_effect = responses
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = airflow_commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
assert len(mock_executor.pending_tasks) == 1
assert len(mock_executor.active_workers.get_all_arns()) == 1
mock_executor.ecs.run_task.call_args_list.clear()
# queue new task
airflow_keys[1] = mock.Mock(spec=tuple)
airflow_commands[1] = _generate_mock_cmd()
mock_executor.execute_async(airflow_keys[1], airflow_commands[1])
assert len(mock_executor.pending_tasks) == 2
# assert that the order of pending tasks is preserved i.e. the first task is 1st etc.
assert mock_executor.pending_tasks[0].key == airflow_keys[0]
assert mock_executor.pending_tasks[0].command == airflow_commands[0]
task["taskArn"] = ARN2
success_response = {"tasks": [task], "failures": []}
responses = [Exception("Failure 1"), success_response]
mock_executor.ecs.run_task.side_effect = responses
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = airflow_commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
assert len(mock_executor.pending_tasks) == 1
assert len(mock_executor.active_workers.get_all_arns()) == 2
mock_executor.ecs.run_task.call_args_list.clear()
responses = [Exception("Failure 1")]
mock_executor.ecs.run_task.side_effect = responses
mock_executor.attempt_task_runs()
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = airflow_commands[0]
assert mock_executor.ecs.run_task.call_args_list[0].kwargs == RUN_TASK_KWARGS
if airflow_version >= (2, 10, 0):
events = [(x.event, x.task_id, x.try_number) for x in mock_executor._task_event_logs]
assert events == [("ecs task submit failure", "task_a", 1)]
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_task_retry_on_api_failure_all_tasks_fail(self, _, mock_executor, caplog):
"""
Test API failure retries.
"""
mock_executor.max_run_task_attempts = "2"
airflow_keys = ["TaskInstanceKey1", "TaskInstanceKey2"]
airflow_commands = [_generate_mock_cmd(), _generate_mock_cmd()]
mock_executor.execute_async(airflow_keys[0], airflow_commands[0])
mock_executor.execute_async(airflow_keys[1], airflow_commands[1])
assert len(mock_executor.pending_tasks) == 2
caplog.set_level("WARNING")
describe_tasks = [
{
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": "FAILED",
"startedAt": dt.datetime.now(),
"stoppedReason": "Task marked as FAILED",
"containers": [
{
"name": "some-ecs-container",
"lastStatus": "STOPPED",
"exitCode": 100,
}
],
},
{
"taskArn": ARN2,
"desiredStatus": "STOPPED",
"lastStatus": "FAILED",
"stoppedReason": "Task marked as REMOVED",
"containers": [
{
"name": "some-ecs-container",
"lastStatus": "STOPPED",
"exitCode": 100,
}
],
},
]
run_tasks = [
{
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
},
{
"taskArn": ARN2,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
},
]
mock_executor.ecs.run_task.side_effect = [
{"tasks": [run_tasks[0]], "failures": []},
{"tasks": [run_tasks[1]], "failures": []},
]
mock_executor.ecs.describe_tasks.side_effect = [{"tasks": describe_tasks, "failures": []}]
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = airflow_commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
assert len(mock_executor.pending_tasks) == 0
assert len(mock_executor.active_workers.get_all_arns()) == 2
mock_executor.sync_running_tasks()
for i in range(2):
assert (
f"Airflow task {airflow_keys[i]} failed due to {describe_tasks[i]['stoppedReason']}. Failure 1 out of 2"
in caplog.messages[i]
)
caplog.clear()
mock_executor.ecs.run_task.call_args_list.clear()
mock_executor.ecs.run_task.side_effect = [
{"tasks": [run_tasks[0]], "failures": []},
{"tasks": [run_tasks[1]], "failures": []},
]
mock_executor.ecs.describe_tasks.side_effect = [{"tasks": describe_tasks, "failures": []}]
mock_executor.attempt_task_runs()
mock_executor.attempt_task_runs()
for i in range(2):
RUN_TASK_KWARGS["overrides"]["containerOverrides"][0]["command"] = airflow_commands[i]
assert mock_executor.ecs.run_task.call_args_list[i].kwargs == RUN_TASK_KWARGS
mock_executor.sync_running_tasks()
for i in range(2):
assert (
f"Airflow task {airflow_keys[i]} has failed a maximum of 2 times. Marking as failed"
in caplog.messages[i]
)
@mock.patch.object(BaseExecutor, "fail")
@mock.patch.object(BaseExecutor, "success")
def test_sync(self, success_mock, fail_mock, mock_executor):
"""Test sync from end-to-end."""
self._mock_sync(mock_executor)
mock_executor.sync_running_tasks()
mock_executor.ecs.describe_tasks.assert_called_once()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
# Task is immediately succeeded.
success_mock.assert_called_once()
fail_mock.assert_not_called()
@mock.patch.object(BaseExecutor, "fail")
@mock.patch.object(BaseExecutor, "success")
@mock.patch.object(EcsTaskCollection, "get_all_arns", return_value=[])
def test_sync_short_circuits_with_no_arns(self, _, success_mock, fail_mock, mock_executor):
self._mock_sync(mock_executor)
mock_executor.sync_running_tasks()
mock_executor.ecs.describe_tasks.assert_not_called()
fail_mock.assert_not_called()
success_mock.assert_not_called()
@mock.patch.object(BaseExecutor, "fail")
@mock.patch.object(BaseExecutor, "success")
def test_failed_sync(self, success_mock, fail_mock, mock_executor):
"""Test success and failure states."""
mock_executor.max_run_task_attempts = "1"
self._mock_sync(mock_executor, State.FAILED)
mock_executor.sync()
mock_executor.ecs.describe_tasks.assert_called_once()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
# Task is immediately failed.
fail_mock.assert_called_once()
success_mock.assert_not_called()
@mock.patch.object(BaseExecutor, "success")
@mock.patch.object(BaseExecutor, "fail")
def test_removed_sync(self, fail_mock, success_mock, mock_executor):
"""A removed task will be treated as a failed task."""
mock_executor.max_run_task_attempts = "1"
self._mock_sync(mock_executor, expected_state=State.REMOVED, set_task_state=State.REMOVED)
mock_executor.sync_running_tasks()
# Task is not stored in active workers.
assert len(mock_executor.active_workers) == 0
# Task is immediately failed.
fail_mock.assert_called_once()
success_mock.assert_not_called()
@mock.patch.object(BaseExecutor, "fail")
@mock.patch.object(BaseExecutor, "success")
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_failed_sync_cumulative_fail(
self, _, success_mock, fail_mock, mock_airflow_key, mock_executor, mock_cmd
):
"""Test that failure_count/attempt_number is cumulative for pending tasks and active workers."""
mock_executor.max_run_task_attempts = "5"
mock_executor.ecs.run_task.return_value = {
"tasks": [],
"failures": [
{"arn": ARN1, "reason": "Sample Failure", "detail": "UnitTest Failure - Please ignore"}
],
}
mock_executor._calculate_next_attempt_time = MagicMock(return_value=utcnow())
task_key = mock_airflow_key()
mock_executor.execute_async(task_key, mock_cmd)
for _ in range(2):
assert len(mock_executor.pending_tasks) == 1
keys = [task.key for task in mock_executor.pending_tasks]
assert task_key in keys
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 1
mock_executor.ecs.run_task.return_value = {
"tasks": [
{
"taskArn": ARN1,
"lastStatus": "",
"desiredStatus": "",
"containers": [{"name": "some-ecs-container"}],
}
],
"failures": [],
}
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 0
assert ARN1 in mock_executor.active_workers.get_all_arns()
mock_executor.ecs.describe_tasks.return_value = {
"tasks": [],
"failures": [
{"arn": ARN1, "reason": "Sample Failure", "detail": "UnitTest Failure - Please ignore"}
],
}
# Call sync_running_tasks and attempt_task_runs 2 times with failures.
for _ in range(2):
mock_executor.sync_running_tasks()
# Ensure task gets removed from active_workers.
assert ARN1 not in mock_executor.active_workers.get_all_arns()
# Ensure task gets back on the pending_tasks queue
assert len(mock_executor.pending_tasks) == 1
keys = [task.key for task in mock_executor.pending_tasks]
assert task_key in keys
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 0
assert ARN1 in mock_executor.active_workers.get_all_arns()
# Task is neither failed nor succeeded.
fail_mock.assert_not_called()
success_mock.assert_not_called()
# run_task failed twice, and passed 3 times
assert mock_executor.ecs.run_task.call_count == 5
# describe_tasks failed 2 times so far
assert mock_executor.ecs.describe_tasks.call_count == 2
# 2 run_task failures + 2 describe_task failures = 4 failures
# Last call should fail the task.
mock_executor.sync_running_tasks()
assert ARN1 not in mock_executor.active_workers.get_all_arns()
fail_mock.assert_called()
success_mock.assert_not_called()
def test_failed_sync_api_exception(self, mock_executor, caplog):
"""Test what happens when ECS sync fails for certain tasks repeatedly."""
self._mock_sync(mock_executor)
mock_executor.ecs.describe_tasks.side_effect = Exception("Test Exception")
mock_executor.sync()
assert "Failed to sync" in caplog.messages[0]
@mock.patch.object(BaseExecutor, "fail")
@mock.patch.object(BaseExecutor, "success")
@mock.patch.object(ecs_executor, "calculate_next_attempt_delay", return_value=dt.timedelta(seconds=0))
def test_failed_sync_api(self, _, success_mock, fail_mock, mock_executor, mock_cmd):
"""Test what happens when ECS sync fails for certain tasks repeatedly."""
airflow_key = "test-key"
mock_executor.execute_async(airflow_key, mock_cmd)
assert len(mock_executor.pending_tasks) == 1
run_task_ret_val = {
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": "RUNNING",
"containers": [
{
"name": "some-ecs-container",
"lastStatus": "STOPPED",
"exitCode": 0,
}
],
}
mock_executor.ecs.run_task.return_value = {"tasks": [run_task_ret_val], "failures": []}
describe_tasks_ret_value = {
"tasks": [],
"failures": [
{"arn": ARN1, "reason": "Sample Failure", "detail": "UnitTest Failure - Please ignore"}
],
}
mock_executor.ecs.describe_tasks.return_value = describe_tasks_ret_value
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 0
assert len(mock_executor.active_workers.get_all_arns()) == 1
task_key = mock_executor.active_workers.arn_to_key[ARN1]
# Call Sync 2 times with failures. The task can only fail max_run_task_attempts times.
for check_count in range(1, int(mock_executor.max_run_task_attempts)):
mock_executor.sync_running_tasks()
assert mock_executor.ecs.describe_tasks.call_count == check_count
# Ensure task gets removed from active_workers.
assert ARN1 not in mock_executor.active_workers.get_all_arns()
# Ensure task gets back on the pending_tasks queue
assert len(mock_executor.pending_tasks) == 1
keys = [task.key for task in mock_executor.pending_tasks]
assert task_key in keys
# Task is neither failed nor succeeded.
fail_mock.assert_not_called()
success_mock.assert_not_called()
mock_executor.attempt_task_runs()
assert len(mock_executor.pending_tasks) == 0
assert len(mock_executor.active_workers.get_all_arns()) == 1
assert ARN1 in mock_executor.active_workers.get_all_arns()
task_key = mock_executor.active_workers.arn_to_key[ARN1]
# Last call should fail the task.
mock_executor.sync_running_tasks()
assert ARN1 not in mock_executor.active_workers.get_all_arns()
fail_mock.assert_called()
success_mock.assert_not_called()
def test_terminate(self, mock_executor):
"""Test that executor can shut everything down; forcing all tasks to unnaturally exit."""
self._mock_sync(mock_executor, State.FAILED)
mock_executor.terminate()
mock_executor.ecs.stop_task.assert_called()
def test_end(self, mock_executor):
"""Test that executor can end successfully; waiting for all tasks to naturally exit."""
mock_executor.sync = partial(self._sync_mock_with_call_counts, mock_executor.sync)
self._mock_sync(mock_executor, State.FAILED)
mock_executor.end(heartbeat_interval=0)
@mock.patch.object(time, "sleep", return_value=None)
def test_end_with_queued_tasks_will_wait(self, _, mock_executor):
"""Test that executor can end successfully; waiting for all tasks to naturally exit."""
sync_call_count = 0
sync_func = mock_executor.sync
def sync_mock():
"""Mock won't work here, because we actually want to call the 'sync' func."""
nonlocal sync_call_count
sync_func()
sync_call_count += 1
if sync_call_count == 1:
# On the second pass, remove the pending task. This is the equivalent of using
# mock side_effects to simulate a pending task the first time (triggering the
# sleep()) and no pending task the second pass, triggering the break and allowing
# the executor to shut down.
mock_executor.active_workers.update_task(
EcsExecutorTask(
ARN2,
"STOPPED",
"STOPPED",
{"exit_code": 0, "name": "some-ecs-container", "last_status": "STOPPED"},
)
)
self.response_task2_json.update({"desiredStatus": "STOPPED", "lastStatus": "STOPPED"})
mock_executor.ecs.describe_tasks.return_value = {
"tasks": [self.response_task2_json],
"failures": [],
}
mock_executor.sync = sync_mock
self._add_mock_task(mock_executor, ARN1)
self._add_mock_task(mock_executor, ARN2)
base_response_task_json = {
"startedAt": dt.datetime.now(),
"containers": [{"name": "some-ecs-container", "lastStatus": "STOPPED", "exitCode": 0}],
}
self.response_task1_json = {
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": "SUCCESS",
**base_response_task_json,
}
self.response_task2_json = {
"taskArn": ARN2,
"desiredStatus": "QUEUED",
"lastStatus": "QUEUED",
**base_response_task_json,
}
mock_executor.ecs.describe_tasks.return_value = {
"tasks": [self.response_task1_json, self.response_task2_json],
"failures": [],
}
mock_executor.end(heartbeat_interval=0)
assert sync_call_count == 2
@pytest.mark.parametrize(
"bad_config",
[
pytest.param({"name": "bad_robot"}, id="executor_config_can_not_overwrite_name"),
pytest.param({"command": "bad_robot"}, id="executor_config_can_not_overwrite_command"),
],
)
def test_executor_config_exceptions(self, bad_config, mock_executor, mock_cmd):
with pytest.raises(ValueError, match='Executor Config should never override "name" or "command"'):
mock_executor.execute_async(mock_airflow_key, mock_cmd, executor_config=bad_config)
assert len(mock_executor.pending_tasks) == 0
@mock.patch.object(ecs_executor_config, "build_task_kwargs")
def test_container_not_found(self, mock_build_task_kwargs, mock_executor):
mock_build_task_kwargs.return_value({"overrides": {"containerOverrides": [{"name": "foo"}]}})
with pytest.raises(KeyError) as raised:
AwsEcsExecutor()
assert raised.match(
re.escape(
"Rendered JSON template does not contain key "
'"overrides[containerOverrides][containers][x][command]"'
)
)
assert len(mock_executor.pending_tasks) == 0
def _mock_sync(
self,
executor: AwsEcsExecutor,
expected_state=TaskInstanceState.SUCCESS,
set_task_state=TaskInstanceState.RUNNING,
) -> None:
"""Mock ECS to the expected state."""
executor.pending_tasks.clear()
self._add_mock_task(executor, ARN1, set_task_state)
response_task_json = {
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": set_task_state,
"containers": [
{
"name": "some-ecs-container",
"lastStatus": "STOPPED",
"exitCode": 100 if expected_state in [State.FAILED, State.QUEUED] else 0,
}
],
}
if not set_task_state == State.REMOVED:
response_task_json["startedAt"] = dt.datetime.now()
assert expected_state == BotoTaskSchema().load(response_task_json).get_task_state()
executor.ecs.describe_tasks.return_value = {"tasks": [response_task_json], "failures": []}
@staticmethod
def _add_mock_task(executor: AwsEcsExecutor, arn: str, state=TaskInstanceState.RUNNING):
task = mock_task(arn, state)
executor.active_workers.add_task(task, mock.Mock(spec=tuple), mock_queue, mock_cmd, mock_config, 1) # type:ignore[arg-type]
def _sync_mock_with_call_counts(self, sync_func: Callable):
"""Mock won't work here, because we actually want to call the 'sync' func."""
# If we call `mock_executor.sync()` here directly we get endless recursion below
# because we are assigning it to itself with `mock_executor.sync = sync_mock`.
self.sync_call_count = 0
sync_func()
self.sync_call_count += 1
@pytest.mark.parametrize(
("desired_status", "last_status", "exit_code", "expected_status"),
[
("RUNNING", "QUEUED", 0, State.QUEUED),
("STOPPED", "RUNNING", 0, State.RUNNING),
("STOPPED", "QUEUED", 0, State.REMOVED),
],
)
def test_update_running_tasks(
self, mock_executor, desired_status, last_status, exit_code, expected_status
):
self._add_mock_task(mock_executor, ARN1)
test_response_task_json = {
"taskArn": ARN1,
"desiredStatus": desired_status,
"lastStatus": last_status,
"containers": [
{
"name": "test_container",
"lastStatus": "QUEUED",
"exitCode": exit_code,
}
],
}
mock_executor.ecs.describe_tasks.return_value = {"tasks": [test_response_task_json], "failures": []}
mock_executor.sync_running_tasks()
if expected_status != State.REMOVED:
assert mock_executor.active_workers.tasks["arn1"].get_task_state() == expected_status
# The task is not removed from active_workers in these states
assert len(mock_executor.active_workers) == 1
else:
# The task is removed from active_workers in this state
assert len(mock_executor.active_workers) == 0
def test_update_running_tasks_success(self, mock_executor):
self._add_mock_task(mock_executor, ARN1)
test_response_task_json = {
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": "STOPPED",
"startedAt": dt.datetime.now(),
"containers": [
{
"name": "test_container",
"lastStatus": "STOPPED",
"exitCode": 0,
}
],
}
patcher = mock.patch(
"airflow.providers.amazon.aws.executors.ecs.ecs_executor.AwsEcsExecutor.success", auth_spec=True
)
mock_success_function = patcher.start()
mock_executor.ecs.describe_tasks.return_value = {"tasks": [test_response_task_json], "failures": []}
mock_executor.sync_running_tasks()
assert len(mock_executor.active_workers) == 0
mock_success_function.assert_called_once()
def test_update_running_tasks_failed(self, mock_executor, caplog):
mock_executor.max_run_task_attempts = "1"
caplog.set_level(logging.WARNING)
self._add_mock_task(mock_executor, ARN1)
test_response_task_json = {
"taskArn": ARN1,
"desiredStatus": "STOPPED",
"lastStatus": "STOPPED",
"startedAt": dt.datetime.now(),
"containers": [
{
"containerArn": "test-container-arn1",
"name": "test_container",
"lastStatus": "STOPPED",
"exitCode": 30,
"reason": "test failure",
}
],
}
patcher = mock.patch(
"airflow.providers.amazon.aws.executors.ecs.ecs_executor.AwsEcsExecutor.fail", auth_spec=True
)
mock_failed_function = patcher.start()
mock_executor.ecs.describe_tasks.return_value = {"tasks": [test_response_task_json], "failures": []}
mock_executor.sync_running_tasks()
assert len(mock_executor.active_workers) == 0
mock_failed_function.assert_called_once()
assert (
"The ECS task failed due to the following containers failing:\ntest-container-arn1 - "
"test failure" in caplog.messages[0]
)
@pytest.mark.skip(reason="Adopting task instances hasn't been ported over to Airflow 3 yet")
def test_try_adopt_task_instances(self, mock_executor):
"""Test that executor can adopt orphaned task instances from a SchedulerJob shutdown event."""
mock_executor.ecs.describe_tasks.return_value = {
"tasks": [
{
"taskArn": "001",
"lastStatus": "RUNNING",
"desiredStatus": "RUNNING",
"containers": [{"name": "some-ecs-container"}],
},
{
"taskArn": "002",
"lastStatus": "RUNNING",
"desiredStatus": "RUNNING",
"containers": [{"name": "another-ecs-container"}],
},
],
"failures": [],
}
orphaned_tasks = [
mock.Mock(spec=TaskInstance),
mock.Mock(spec=TaskInstance),
mock.Mock(spec=TaskInstance),
]
orphaned_tasks[0].external_executor_id = "001" # Matches a running task_arn
orphaned_tasks[1].external_executor_id = "002" # Matches a running task_arn
orphaned_tasks[2].external_executor_id = None # One orphaned task has no external_executor_id
for task in orphaned_tasks:
task.try_number = 1
not_adopted_tasks = mock_executor.try_adopt_task_instances(orphaned_tasks)
mock_executor.ecs.describe_tasks.assert_called_once()
# Two of the three tasks should be adopted.
assert len(orphaned_tasks) - 1 == len(mock_executor.active_workers)
# The remaining one task is unable to be adopted.
assert len(not_adopted_tasks) == 1
| TestAwsEcsExecutor |
python | TheAlgorithms__Python | electronics/circular_convolution.py | {
"start": 688,
"end": 3456
} | class ____:
"""
This class stores the first and second signal and performs the circular convolution
"""
def __init__(self) -> None:
"""
First signal and second signal are stored as 1-D array
"""
self.first_signal = [2, 1, 2, -1]
self.second_signal = [1, 2, 3, 4]
def circular_convolution(self) -> list[float]:
"""
This function performs the circular convolution of the first and second signal
using matrix method
Usage:
>>> convolution = CircularConvolution()
>>> convolution.circular_convolution()
[10.0, 10.0, 6.0, 14.0]
>>> convolution.first_signal = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6]
>>> convolution.second_signal = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5]
>>> convolution.circular_convolution()
[5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08]
>>> convolution.first_signal = [-1, 1, 2, -2]
>>> convolution.second_signal = [0.5, 1, -1, 2, 0.75]
>>> convolution.circular_convolution()
[6.25, -3.0, 1.5, -2.0, -2.75]
>>> convolution.first_signal = [1, -1, 2, 3, -1]
>>> convolution.second_signal = [1, 2, 3]
>>> convolution.circular_convolution()
[8.0, -2.0, 3.0, 4.0, 11.0]
"""
length_first_signal = len(self.first_signal)
length_second_signal = len(self.second_signal)
max_length = max(length_first_signal, length_second_signal)
# create a zero matrix of max_length x max_length
matrix = [[0] * max_length for i in range(max_length)]
# fills the smaller signal with zeros to make both signals of same length
if length_first_signal < length_second_signal:
self.first_signal += [0] * (max_length - length_first_signal)
elif length_first_signal > length_second_signal:
self.second_signal += [0] * (max_length - length_second_signal)
"""
Fills the matrix in the following way assuming 'x' is the signal of length 4
[
[x[0], x[3], x[2], x[1]],
[x[1], x[0], x[3], x[2]],
[x[2], x[1], x[0], x[3]],
[x[3], x[2], x[1], x[0]]
]
"""
for i in range(max_length):
rotated_signal = deque(self.second_signal)
rotated_signal.rotate(i)
for j, item in enumerate(rotated_signal):
matrix[i][j] += item
# multiply the matrix with the first signal
final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal))
# rounding-off to two decimal places
return [float(round(i, 2)) for i in final_signal]
if __name__ == "__main__":
doctest.testmod()
| CircularConvolution |
python | getlogbook__logbook | src/logbook/queues.py | {
"start": 5756,
"end": 7979
} | class ____(Handler):
"""A handler that acts as a ZeroMQ publisher, which publishes each record
as json dump. Requires the pyzmq library.
The queue will be filled with JSON exported log records. To receive such
log records from a queue you can use the :class:`ZeroMQSubscriber`.
If `multi` is set to `True`, the handler will use a `PUSH` socket to
publish the records. This allows multiple handlers to use the same `uri`.
The records can be received by using the :class:`ZeroMQSubscriber` with
`multi` set to `True`.
Example setup::
handler = ZeroMQHandler("tcp://127.0.0.1:5000")
"""
def __init__(
self,
uri=None,
level=NOTSET,
filter=None,
bubble=False,
context=None,
multi=False,
):
Handler.__init__(self, level, filter, bubble)
try:
import zmq
except ImportError:
raise RuntimeError("The pyzmq library is required for the ZeroMQHandler.")
#: the zero mq context
self.context = context or zmq.Context()
if multi:
#: the zero mq socket.
self.socket = self.context.socket(zmq.PUSH)
if uri is not None:
self.socket.connect(uri)
else:
#: the zero mq socket.
self.socket = self.context.socket(zmq.PUB)
if uri is not None:
self.socket.bind(uri)
def export_record(self, record):
"""Exports the record into a dictionary ready for JSON dumping."""
return record.to_dict(json_safe=True)
def emit(self, record):
self.socket.send(json.dumps(self.export_record(record)).encode("utf-8"))
def close(self, linger=-1):
self.socket.close(linger)
def __del__(self):
# When the Handler is deleted we must close our socket in a
# non-blocking fashion (using linger).
# Otherwise it can block indefinitely, for example if the Subscriber is
# not reachable.
# If messages are pending on the socket, we wait 100ms for them to be
# sent then we discard them.
if hasattr(self, "socket"):
self.close(linger=100)
| ZeroMQHandler |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py | {
"start": 75388,
"end": 76709
} | class ____(Qwen2AudioEncoderLayer):
def __init__(self, config: Qwen2_5OmniAudioEncoderConfig):
super().__init__(config)
self.self_attn = Qwen2_5OmniAudioAttention(config)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states = self.self_attn(
hidden_states=hidden_states,
cu_seqlens=cu_seqlens,
attention_mask=attention_mask,
**kwargs,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
hidden_states = residual + hidden_states
if hidden_states.dtype == torch.float16:
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
outputs = (hidden_states,)
return outputs
| Qwen2_5OmniAudioEncoderLayer |
python | PyCQA__pylint | tests/functional/n/no/no_warning_docstring.py | {
"start": 521,
"end": 881
} | class ____(BBBB):
''' class CCCC '''
def __init__(self):
BBBB.__init__(self)
# should ignore docstring since CCCC is inherited from BBBB which is
# inherited from AAAA containing method2
if __revision__:
def method2(self):
AAAA.method2(self)
else:
def method2(self):
AAAA.method1(self)
| CCCC |
python | Pylons__pyramid | src/pyramid/config/adapters.py | {
"start": 276,
"end": 13920
} | class ____:
@action_method
def add_subscriber(self, subscriber, iface=None, **predicates):
"""Add an event :term:`subscriber` for the event stream
implied by the supplied ``iface`` interface.
The ``subscriber`` argument represents a callable object (or a
:term:`dotted Python name` which identifies a callable); it will be
called with a single object ``event`` whenever :app:`Pyramid` emits
an :term:`event` associated with the ``iface``, which may be an
:term:`interface` or a class or a :term:`dotted Python name` to a
global object representing an interface or a class.
Using the default ``iface`` value, ``None`` will cause the subscriber
to be registered for all event types. See :ref:`events_chapter` for
more information about events and subscribers.
Any number of predicate keyword arguments may be passed in
``**predicates``. Each predicate named will narrow the set of
circumstances in which the subscriber will be invoked. Each named
predicate must have been registered via
:meth:`pyramid.config.Configurator.add_subscriber_predicate` before it
can be used. See :ref:`subscriber_predicates` for more information.
.. versionadded:: 1.4
The ``**predicates`` argument.
"""
dotted = self.maybe_dotted
subscriber, iface = dotted(subscriber), dotted(iface)
if iface is None:
iface = (Interface,)
if not isinstance(iface, (tuple, list)):
iface = (iface,)
def register():
predlist = self.get_predlist('subscriber')
order, preds, phash = predlist.make(self, **predicates)
derived_predicates = [self._derive_predicate(p) for p in preds]
derived_subscriber = self._derive_subscriber(
subscriber, derived_predicates
)
intr.update(
{
'phash': phash,
'order': order,
'predicates': preds,
'derived_predicates': derived_predicates,
'derived_subscriber': derived_subscriber,
}
)
self.registry.registerHandler(derived_subscriber, iface)
intr = self.introspectable(
'subscribers',
id(subscriber),
self.object_description(subscriber),
'subscriber',
)
intr['subscriber'] = subscriber
intr['interfaces'] = iface
self.action(None, register, introspectables=(intr,))
return subscriber
def _derive_predicate(self, predicate):
if eventonly(predicate):
def derived_predicate(*arg):
return predicate(arg[0])
# seems pointless to try to fix __doc__, __module__, etc as
# predicate will invariably be an instance
else:
derived_predicate = predicate
return derived_predicate
def _derive_subscriber(self, subscriber, predicates):
if eventonly(subscriber):
def derived_subscriber(*arg):
return subscriber(arg[0])
if hasattr(subscriber, '__name__'):
update_wrapper(derived_subscriber, subscriber)
else:
derived_subscriber = subscriber
if not predicates:
return derived_subscriber
def subscriber_wrapper(*arg):
# We need to accept *arg and pass it along because zope subscribers
# are designed awkwardly. Notification via
# registry.adapter.subscribers will always call an associated
# subscriber with all of the objects involved in the subscription
# lookup, despite the fact that the event sender always has the
# option to attach those objects to the event object itself, and
# almost always does.
#
# The "eventonly" jazz sprinkled in this function and related
# functions allows users to define subscribers and predicates which
# accept only an event argument without needing to accept the rest
# of the adaptation arguments. Had I been smart enough early on to
# use .subscriptions to find the subscriber functions in order to
# call them manually with a single "event" argument instead of
# relying on .subscribers to both find and call them implicitly
# with all args, the eventonly hack would not have been required.
# At this point, though, using .subscriptions and manual execution
# is not possible without badly breaking backwards compatibility.
if all(predicate(*arg) for predicate in predicates):
return derived_subscriber(*arg)
if hasattr(subscriber, '__name__'):
update_wrapper(subscriber_wrapper, subscriber)
return subscriber_wrapper
@action_method
def add_subscriber_predicate(
self, name, factory, weighs_more_than=None, weighs_less_than=None
):
"""
.. versionadded:: 1.4
Adds a subscriber predicate factory. The associated subscriber
predicate can later be named as a keyword argument to
:meth:`pyramid.config.Configurator.add_subscriber` in the
``**predicates`` anonymous keyword argument dictionary.
``name`` should be the name of the predicate. It must be a valid
Python identifier (it will be used as a ``**predicates`` keyword
argument to :meth:`~pyramid.config.Configurator.add_subscriber`).
``factory`` should be a :term:`predicate factory` or :term:`dotted
Python name` which refers to a predicate factory.
See :ref:`subscriber_predicates` for more information.
"""
self._add_predicate(
'subscriber',
name,
factory,
weighs_more_than=weighs_more_than,
weighs_less_than=weighs_less_than,
)
@action_method
def add_response_adapter(self, adapter, type_or_iface):
"""When an object of type (or interface) ``type_or_iface`` is
returned from a view callable, Pyramid will use the adapter
``adapter`` to convert it into an object which implements the
:class:`pyramid.interfaces.IResponse` interface. If ``adapter`` is
None, an object returned of type (or interface) ``type_or_iface``
will itself be used as a response object.
``adapter`` and ``type_or_interface`` may be Python objects or
strings representing dotted names to importable Python global
objects.
See :ref:`using_iresponse` for more information."""
adapter = self.maybe_dotted(adapter)
type_or_iface = self.maybe_dotted(type_or_iface)
def register():
reg = self.registry
if adapter is None:
reg.registerSelfAdapter((type_or_iface,), IResponse)
else:
reg.registerAdapter(adapter, (type_or_iface,), IResponse)
discriminator = (IResponse, type_or_iface)
intr = self.introspectable(
'response adapters',
discriminator,
self.object_description(adapter),
'response adapter',
)
intr['adapter'] = adapter
intr['type'] = type_or_iface
self.action(discriminator, register, introspectables=(intr,))
def add_default_response_adapters(self):
# cope with WebOb response objects that aren't decorated with IResponse
self.add_response_adapter(None, WebobResponse)
@action_method
def add_traverser(self, adapter, iface=None):
"""
The superdefault :term:`traversal` algorithm that :app:`Pyramid` uses
is explained in :ref:`traversal_algorithm`. Though it is rarely
necessary, this default algorithm can be swapped out selectively for
a different traversal pattern via configuration. The section
entitled :ref:`changing_the_traverser` details how to create a
traverser class.
For example, to override the superdefault traverser used by Pyramid,
you might do something like this:
.. code-block:: python
from myapp.traversal import MyCustomTraverser
config.add_traverser(MyCustomTraverser)
This would cause the Pyramid superdefault traverser to never be used;
instead all traversal would be done using your ``MyCustomTraverser``
class, no matter which object was returned by the :term:`root
factory` of this application. Note that we passed no arguments to
the ``iface`` keyword parameter. The default value of ``iface``,
``None`` represents that the registered traverser should be used when
no other more specific traverser is available for the object returned
by the root factory.
However, more than one traversal algorithm can be active at the same
time. The traverser used can depend on the result of the :term:`root
factory`. For instance, if your root factory returns more than one
type of object conditionally, you could claim that an alternate
traverser adapter should be used against one particular class or
interface returned by that root factory. When the root factory
returned an object that implemented that class or interface, a custom
traverser would be used. Otherwise, the default traverser would be
used. The ``iface`` argument represents the class of the object that
the root factory might return or an :term:`interface` that the object
might implement.
To use a particular traverser only when the root factory returns a
particular class:
.. code-block:: python
config.add_traverser(MyCustomTraverser, MyRootClass)
When more than one traverser is active, the "most specific" traverser
will be used (the one that matches the class or interface of the
value returned by the root factory most closely).
Note that either ``adapter`` or ``iface`` can be a :term:`dotted
Python name` or a Python object.
See :ref:`changing_the_traverser` for more information.
"""
iface = self.maybe_dotted(iface)
adapter = self.maybe_dotted(adapter)
def register(iface=iface):
if iface is None:
iface = Interface
self.registry.registerAdapter(adapter, (iface,), ITraverser)
discriminator = ('traverser', iface)
intr = self.introspectable(
'traversers',
discriminator,
'traverser for %r' % iface,
'traverser',
)
intr['adapter'] = adapter
intr['iface'] = iface
self.action(discriminator, register, introspectables=(intr,))
@action_method
def add_resource_url_adapter(self, adapter, resource_iface=None):
"""
.. versionadded:: 1.3
When you add a traverser as described in
:ref:`changing_the_traverser`, it's convenient to continue to use the
:meth:`pyramid.request.Request.resource_url` API. However, since the
way traversal is done may have been modified, the URLs that
``resource_url`` generates by default may be incorrect when resources
are returned by a custom traverser.
If you've added a traverser, you can change how
:meth:`~pyramid.request.Request.resource_url` generates a URL for a
specific type of resource by calling this method.
The ``adapter`` argument represents a class that implements the
:class:`~pyramid.interfaces.IResourceURL` interface. The class
constructor should accept two arguments in its constructor (the
resource and the request) and the resulting instance should provide
the attributes detailed in that interface (``virtual_path`` and
``physical_path``, in particular).
The ``resource_iface`` argument represents a class or interface that
the resource should possess for this url adapter to be used when
:meth:`pyramid.request.Request.resource_url` looks up a resource url
adapter. If ``resource_iface`` is not passed, or it is passed as
``None``, the url adapter will be used for every type of resource.
See :ref:`changing_resource_url` for more information.
"""
adapter = self.maybe_dotted(adapter)
resource_iface = self.maybe_dotted(resource_iface)
def register(resource_iface=resource_iface):
if resource_iface is None:
resource_iface = Interface
self.registry.registerAdapter(
adapter, (resource_iface, Interface), IResourceURL
)
discriminator = ('resource url adapter', resource_iface)
intr = self.introspectable(
'resource url adapters',
discriminator,
'resource url adapter for resource iface %r' % resource_iface,
'resource url adapter',
)
intr['adapter'] = adapter
intr['resource_iface'] = resource_iface
self.action(discriminator, register, introspectables=(intr,))
def eventonly(callee):
# we do not count a function as eventonly if it accepts *args
# which will open up the possibility for the function to receive
# all of the args
return takes_one_arg(callee, argname='event', allow_varargs=False)
| AdaptersConfiguratorMixin |
python | doocs__leetcode | solution/1100-1199/1133.Largest Unique Number/Solution.py | {
"start": 0,
"end": 173
} | class ____:
def largestUniqueNumber(self, nums: List[int]) -> int:
cnt = Counter(nums)
return max((x for x, v in cnt.items() if v == 1), default=-1)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 4127,
"end": 5804
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_single_tensor_raises(self):
tensor = constant_op.constant(1)
with self.assertRaisesRegex(TypeError, "proper"):
check_ops.assert_proper_iterable(tensor)
@test_util.run_in_graph_and_eager_modes
def test_single_sparse_tensor_raises(self):
ten = sparse_tensor.SparseTensor(
indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
with self.assertRaisesRegex(TypeError, "proper"):
check_ops.assert_proper_iterable(ten)
@test_util.run_in_graph_and_eager_modes
def test_single_ndarray_raises(self):
array = np.array([1, 2, 3])
with self.assertRaisesRegex(TypeError, "proper"):
check_ops.assert_proper_iterable(array)
@test_util.run_in_graph_and_eager_modes
def test_single_string_raises(self):
mystr = "hello"
with self.assertRaisesRegex(TypeError, "proper"):
check_ops.assert_proper_iterable(mystr)
@test_util.run_in_graph_and_eager_modes
def test_non_iterable_object_raises(self):
non_iterable = 1234
with self.assertRaisesRegex(TypeError, "to be iterable"):
check_ops.assert_proper_iterable(non_iterable)
@test_util.run_in_graph_and_eager_modes
def test_list_does_not_raise(self):
list_of_stuff = [
constant_op.constant([11, 22]), constant_op.constant([1, 2])
]
check_ops.assert_proper_iterable(list_of_stuff)
@test_util.run_in_graph_and_eager_modes
def test_generator_does_not_raise(self):
generator_of_stuff = (constant_op.constant([11, 22]), constant_op.constant(
[1, 2]))
check_ops.assert_proper_iterable(generator_of_stuff)
| AssertProperIterableTest |
python | huggingface__transformers | src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py | {
"start": 2190,
"end": 24598
} | class ____(PreTrainedModel, GenerationMixin):
r"""
[`SpeechEncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with
one of the base model classes of the library as encoder and another one as decoder when created with the
:meth*~transformers.AutoModel.from_pretrained* class method for the encoder and
:meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder.
"""
config: SpeechEncoderDecoderConfig
base_model_prefix = "speech_encoder_decoder"
main_input_name = "inputs"
input_modalities = "audio"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
def __init__(
self,
config: Optional[PreTrainedConfig] = None,
encoder: Optional[PreTrainedModel] = None,
decoder: Optional[PreTrainedModel] = None,
):
r"""
encoder (`PreTrainedModel`, *optional*):
The encoder model to use.
decoder (`PreTrainedModel`, *optional*):
The decoder model to use.
"""
if config is None and (encoder is None or decoder is None):
raise ValueError("Either a configuration or an encoder and a decoder has to be provided.")
if config is None:
config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config)
else:
if not isinstance(config, self.config_class):
raise ValueError(f"Config: {config} has to be of type {self.config_class}")
if config.decoder.cross_attention_hidden_size is not None:
if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size:
raise ValueError(
"If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal"
f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for"
f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for"
" `config.encoder.hidden_size`."
)
# initialize with config
# make sure input & output embeddings is not tied
config.tie_word_embeddings = False
super().__init__(config)
if encoder is None:
encoder = AutoModel.from_config(config.encoder)
if decoder is None:
decoder = AutoModelForCausalLM.from_config(config.decoder)
self.encoder = encoder
self.decoder = decoder
if self.encoder.config.to_dict() != self.config.encoder.to_dict():
logger.warning(
f"Config of the encoder: {self.encoder.__class__} is overwritten by shared encoder config:"
f" {self.config.encoder}"
)
if self.decoder.config.to_dict() != self.config.decoder.to_dict():
logger.warning(
f"Config of the decoder: {self.decoder.__class__} is overwritten by shared decoder config:"
f" {self.config.decoder}"
)
# make sure that the individual model's config refers to the shared config
# so that the updates to the config will be synced
self.config.encoder._attn_implementation = self.encoder.config._attn_implementation
self.config.decoder._attn_implementation = self.decoder.config._attn_implementation
self.encoder.config = self.config.encoder
self.decoder.config = self.config.decoder
# get encoder output hidden size
self.encoder_output_dim = getattr(config.encoder, "output_hidden_size", config.encoder.hidden_size)
if (
self.encoder_output_dim != self.decoder.config.hidden_size
and self.decoder.config.cross_attention_hidden_size is None
):
# encoder outputs might need to be projected to different dimension for decoder
self.enc_to_dec_proj = nn.Linear(self.encoder.config.hidden_size, self.decoder.config.hidden_size)
if self.encoder.get_output_embeddings() is not None:
raise ValueError(
f"The encoder {self.encoder} should not have a LM Head. Please use a model without LM Head"
)
self.post_init()
def get_input_embeddings(self):
return self.decoder.get_input_embeddings()
def get_output_embeddings(self):
return self.decoder.get_output_embeddings()
def set_output_embeddings(self, new_embeddings):
return self.decoder.set_output_embeddings(new_embeddings)
def freeze_feature_encoder(self):
"""
Calling this function will disable the gradient computation for the feature encoder of the speech encoder so
that its parameters will not be updated during training.
"""
self.encoder.freeze_feature_encoder()
@classmethod
def from_encoder_decoder_pretrained(
cls,
encoder_pretrained_model_name_or_path: Optional[str] = None,
decoder_pretrained_model_name_or_path: Optional[str] = None,
*model_args,
**kwargs,
) -> PreTrainedModel:
r"""
Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
checkpoints.
The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
the model, you need to first set it back in training mode with `model.train()`.
Params:
encoder_pretrained_model_name_or_path (`str`, *optional*):
Information necessary to initiate the encoder. Can be either:
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a *directory* containing model weights saved using
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
Information necessary to initiate the decoder. Can be either:
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a *directory* containing model weights saved using
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
model_args (remaining positional arguments, *optional*):
All remaining positional arguments will be passed to the underlying model's `__init__` method.
kwargs (remaining dictionary of keyword arguments, *optional*):
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
`output_attentions=True`).
- To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
- To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
- To update the parent model configuration, do not use a prefix for each configuration parameter.
Behaves differently depending on whether a `config` is provided or automatically loaded.
Example:
```python
>>> from transformers import SpeechEncoderDecoderModel
>>> # initialize a wav2vec2bert from a pretrained Wav2Vec2 and a pretrained BERT model. Note that the cross-attention layers will be randomly initialized
>>> model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(
... "facebook/wav2vec2-base-960h", "google-bert/bert-base-uncased"
... )
>>> # saving model after fine-tuning
>>> model.save_pretrained("./wav2vec2bert")
>>> # load fine-tuned model
>>> model = SpeechEncoderDecoderModel.from_pretrained("./wav2vec2bert")
```"""
kwargs_encoder = {
argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_")
}
kwargs_decoder = {
argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
}
# remove encoder, decoder kwargs from kwargs
for key in kwargs_encoder:
del kwargs["encoder_" + key]
for key in kwargs_decoder:
del kwargs["decoder_" + key]
# Load and initialize the encoder and decoder
# The distinction between encoder and decoder at the model level is made
# by the value of the flag `is_decoder` that we need to set correctly.
encoder = kwargs_encoder.pop("model", None)
if encoder is None:
if encoder_pretrained_model_name_or_path is None:
raise ValueError(
"If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has "
"to be defined."
)
if "config" not in kwargs_encoder:
encoder_config, kwargs_encoder = AutoConfig.from_pretrained(
encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True
)
if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True:
logger.info(
f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model "
"from a decoder model. Cross-attention and causal mask are disabled."
)
encoder_config.is_decoder = False
encoder_config.add_cross_attention = False
kwargs_encoder["config"] = encoder_config
encoder = AutoModel.from_pretrained(encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder)
decoder = kwargs_decoder.pop("model", None)
if decoder is None:
if decoder_pretrained_model_name_or_path is None:
raise ValueError(
"If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has "
"to be defined."
)
if "config" not in kwargs_decoder:
decoder_config, kwargs_decoder = AutoConfig.from_pretrained(
decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
)
if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
logger.info(
f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention"
f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if"
f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
)
decoder_config.is_decoder = True
decoder_config.add_cross_attention = True
kwargs_decoder["config"] = decoder_config
if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
logger.warning(
f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
"make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
"passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a "
"`decoder_config` to `.from_encoder_decoder_pretrained(...)`"
)
decoder = AutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
# instantiate config with corresponding kwargs
config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs)
# make sure input & output embeddings is not tied
config.tie_word_embeddings = False
return cls(encoder=encoder, decoder=decoder, config=config)
@auto_docstring
def forward(
self,
inputs: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
encoder_outputs: Optional[tuple[torch.FloatTensor]] = None,
past_key_values: Optional[Cache] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
input_values: Optional[torch.FloatTensor] = None,
input_features: Optional[torch.FloatTensor] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
r"""
inputs (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, feature_dim)`, *optional*):
Float values of input raw speech waveform or speech features. Values can be obtained by loading a `.flac`
or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.*
via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
To prepare the array into `inputs`, either the [`Wav2Vec2Processor`] or
[`Speech2TextProcessor`] should be used for padding and conversion into a tensor of type
`torch.FloatTensor`.
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
`past_key_values`).
For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the
right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`.
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
representation. This is useful if you want more control over how to convert `decoder_input_ids` indices
into associated vectors than the model's internal embedding lookup matrix.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0,
..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file
into an array of type *list[float]* or a *numpy.ndarray*, *e.g.* via the torchcodec library
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
To prepare the array into *input_values*, the [`Wav2Vec2Processor`] should be used for padding and conversion
into a tensor of type *torch.FloatTensor*. See [`Wav2Vec2Processor.__call__`] for details.
Examples:
```python
>>> from transformers import SpeechEncoderDecoderModel, AutoProcessor
>>> from datasets import load_dataset
>>> import torch
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
>>> model = SpeechEncoderDecoderModel.from_pretrained("facebook/wav2vec2-xls-r-300m-en-to-15")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> input_values = processor(ds[0]["audio"]["array"], return_tensors="pt").input_values
>>> # Inference: Translate English speech to German
>>> generated = model.generate(input_values)
>>> decoded = processor.batch_decode(generated, skip_special_tokens=True)[0]
>>> decoded
'Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen heißen zu können.'
>>> # Training: Train model on English transcription
>>> labels = processor(text=ds[0]["text"], return_tensors="pt").input_ids
>>> loss = model(input_values, labels=labels).loss
>>> loss.backward()
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")}
kwargs_decoder = {
argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
}
if "num_items_in_batch" in kwargs_encoder:
kwargs_decoder["num_items_in_batch"] = kwargs_encoder.pop("num_items_in_batch", None)
if encoder_outputs is None:
if inputs is None:
if input_values is not None and input_features is not None:
raise ValueError("You cannot specify both input_values and input_features at the same time")
elif input_values is not None:
inputs = input_values
elif input_features is not None:
inputs = input_features
else:
raise ValueError("You have to specify either input_values or input_features")
encoder_outputs = self.encoder(
inputs,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
**kwargs_encoder,
)
elif isinstance(encoder_outputs, tuple):
encoder_outputs = BaseModelOutput(*encoder_outputs)
encoder_hidden_states = encoder_outputs[0]
# optionally project encoder_hidden_states
if (
self.encoder_output_dim != self.decoder.config.hidden_size
and self.decoder.config.cross_attention_hidden_size is None
):
encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
# compute correct encoder attention mask
if attention_mask is not None:
encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(
encoder_hidden_states.shape[1], attention_mask
)
else:
encoder_attention_mask = None
if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):
decoder_input_ids = shift_tokens_right(
labels, self.config.pad_token_id, self.config.decoder_start_token_id
)
# Decode
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
inputs_embeds=decoder_inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
use_cache=use_cache,
past_key_values=past_key_values,
return_dict=return_dict,
**kwargs_decoder,
)
# Compute loss independent from decoder (as some shift the logits inside them)
loss = None
if labels is not None:
logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.reshape(-1))
if not return_dict:
if loss is not None:
return (loss,) + decoder_outputs + encoder_outputs
else:
return decoder_outputs + encoder_outputs
return Seq2SeqLMOutput(
loss=loss,
logits=decoder_outputs.logits,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_hidden_states,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
def resize_token_embeddings(self, *args, **kwargs):
raise NotImplementedError(
"Resizing the embedding layers via the SpeechEncoderDecoderModel directly is not supported. Please use the"
" respective methods of the wrapped decoder object (model.decoder.resize_token_embeddings(...))"
)
__all__ = ["SpeechEncoderDecoderModel"]
| SpeechEncoderDecoderModel |
python | run-llama__llama_index | llama-index-integrations/agent/llama-index-agent-azure/llama_index/agent/azure_foundry_agent/base.py | {
"start": 918,
"end": 17969
} | class ____(BaseWorkflowAgent):
"""
Workflow-compatible Azure Foundry Agent for multi-agent orchestration.
Inherits from BaseWorkflowAgent.
Implements async methods for workflow integration using the async Azure SDK.
"""
def __init__(
self,
endpoint: str,
model: str = "gpt-4o-mini",
name: str = "azure-agent",
instructions: str = "You are a helpful agent",
thread_id: Optional[str] = None,
agent_id: Optional[str] = None,
run_retrieve_sleep_time: float = 1.0,
verbose: bool = False,
**kwargs,
):
super().__init__(name=name, llm=MockLLM(), **kwargs)
self._endpoint = endpoint
self._model = model
self._instructions = instructions
self._run_retrieve_sleep_time = run_retrieve_sleep_time
self._thread_id = thread_id
self._agent_id = agent_id
self._agent = None
self._run_id = None
self._credential = DefaultAzureCredential()
self._client = AIProjectClient(endpoint=endpoint, credential=self._credential)
self._verbose = verbose
# self.tools = tools if tools is not None else []
self._toolset = ToolSet()
async def _ensure_agent(self, tools: Sequence[AsyncBaseTool]) -> None:
if self._agent is None:
if self._agent_id is not None:
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Fetching existing agent with id={self._agent_id}"
)
self._agent = await self._client.agents.get_agent(self._agent_id)
else:
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Creating new agent with model={self._model}, name={self.name}"
)
func_tools = []
for t in tools or []:
if isinstance(t, LLamaIndexFunctionTool):
func_tools.append(t.fn)
if func_tools:
self._toolset.add(FunctionTool(functions=set(func_tools)))
self._agent = await self._client.agents.create_agent(
model=self._model,
name=self.name,
instructions=self._instructions,
toolset=self._toolset,
)
self._agent_id = self._agent.id
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Created agent with id={self._agent_id}"
)
if self._thread_id is None:
if self._verbose:
print(f"[AzureFoundryWorkflowAgent] Creating new thread.")
thread = await self._client.agents.threads.create()
self._thread_id = thread.id
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Created thread with id={self._thread_id}"
)
def _llama_to_azure_content_blocks(
self, chat_messages: List[ChatMessage]
) -> list[MessageInputContentBlock]:
"""
Internal: Convert a list of LlamaIndex ChatMessage to a list of Azure MessageInputContentBlock.
Supports text and image blocks. Extend as needed for audio/document.
"""
from azure.ai.agents.models import (
MessageInputTextBlock,
MessageInputImageFileBlock,
MessageInputImageUrlBlock,
MessageImageFileParam,
MessageImageUrlParam,
)
azure_blocks: list[MessageInputContentBlock] = []
for msg in chat_messages:
for block in getattr(msg, "blocks", []):
if isinstance(block, TextBlock):
azure_blocks.append(MessageInputTextBlock(text=block.text))
elif isinstance(block, ImageBlock):
if block.path or block.image:
file_id = str(block.path) if block.path else None
if file_id:
azure_blocks.append(
MessageInputImageFileBlock(
image_file=MessageImageFileParam(
file_id=file_id, detail=block.detail
)
)
)
elif block.url:
azure_blocks.append(
MessageInputImageUrlBlock(
image_url=MessageImageUrlParam(
url=str(block.url), detail=block.detail
)
)
)
else:
raise ValueError(f"Unsupported block type: {type(block)}")
return azure_blocks
async def take_step(
self,
ctx: Context,
llm_input: List[ChatMessage],
tools: Sequence[AsyncBaseTool],
memory: BaseMemory,
) -> AgentOutput:
"""
Take a single step with the Azure Foundry agent.
Interacts with Azure backend and returns AgentOutput (response, tool_calls, etc).
"""
# Convert the entire llm_input to Azure content blocks
azure_content_blocks = (
self._llama_to_azure_content_blocks(llm_input) if llm_input else []
)
await self._ensure_agent(tools=tools)
assert self._thread_id is not None, (
"Thread ID must be set after _ensure_agent()"
)
assert self._agent is not None, "Agent must be set after _ensure_agent()"
tool_calls = []
response_msg = None
# Only send a user message if there is new user input
if azure_content_blocks:
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Sending user message blocks to thread_id={self._thread_id}"
)
await self._client.agents.messages.create(
thread_id=self._thread_id, role="user", content=azure_content_blocks
)
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Starting run for agent_id={self._agent.id} on thread_id={self._thread_id}"
)
run = await self._client.agents.runs.create(
thread_id=self._thread_id, agent_id=self._agent.id
)
self._run_id = run.id
current_run = run
while current_run.status in ["queued", "in_progress", "requires_action"]:
await asyncio.sleep(self._run_retrieve_sleep_time)
current_run = await self._client.agents.runs.get(
thread_id=self._thread_id, run_id=self._run_id
)
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Run status: {current_run.status}"
)
if current_run.status == "requires_action":
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Run requires action: {getattr(current_run, 'required_action', None)}"
)
break
if current_run.status == "failed":
return AgentOutput(
response=ChatMessage(role="assistant", content="Run failed."),
tool_calls=[],
raw=current_run,
current_agent_name=self.name,
)
required_action = getattr(current_run, "required_action", None)
if (
required_action
and getattr(required_action, "type", None) == "submit_tool_outputs"
and isinstance(required_action, SubmitToolOutputsAction)
):
submit_tool_outputs = required_action.submit_tool_outputs
for call in getattr(submit_tool_outputs, "tool_calls", []):
# For function tool calls
if isinstance(call, RequiredFunctionToolCall):
function = getattr(call, "function", None)
tool_name = getattr(function, "name", "") if function else ""
arguments = (
getattr(function, "arguments", "{}") if function else "{}"
)
try:
tool_kwargs = json.loads(arguments)
except Exception:
tool_kwargs = {}
tool_calls.append(
ToolSelection(
tool_id=getattr(call, "id", ""),
tool_name=tool_name,
tool_kwargs=tool_kwargs,
)
)
# Get the latest assistant message if available
latest_msg = None
async for msg in self._client.agents.messages.list(
thread_id=self._thread_id, run_id=self._run_id, order="desc"
):
if getattr(msg, "role", None) == "assistant" and getattr(
msg, "content", None
):
latest_msg = self._from_azure_thread_message(msg)
break
# If no assistant message found, try to get the last assistant message in the thread
if not latest_msg:
async for msg in self._client.agents.messages.list(
thread_id=self._thread_id, order="desc"
):
if getattr(msg, "role", None) == "assistant" and getattr(
msg, "content", None
):
latest_msg = self._from_azure_thread_message(msg)
break
response_msg = (
latest_msg
if latest_msg
else ChatMessage(role="assistant", content="No response from agent.")
)
else:
# No new user input: fetch the latest assistant message after tool call resolution
latest_msg = None
async for msg in self._client.agents.messages.list(
thread_id=self._thread_id, order="desc"
):
if getattr(msg, "role", None) == "assistant" and getattr(
msg, "content", None
):
latest_msg = self._from_azure_thread_message(msg)
break
response_msg = (
latest_msg
if latest_msg
else ChatMessage(role="assistant", content="No response from agent.")
)
return AgentOutput(
response=response_msg,
tool_calls=tool_calls,
raw=current_run if azure_content_blocks else None,
current_agent_name=self.name,
)
async def handle_tool_call_results(
self, ctx: Context, results: List[ToolCallResult], memory: BaseMemory
) -> None:
"""
Handle tool call results for Azure Foundry agent.
Submits results to Azure backend and updates state/context as needed.
Waits for run to reach a terminal state or another action required.
Also appends tool call results to the scratchpad for context tracking.
"""
# Convert ToolCallResult to Azure tool_outputs format
tool_outputs = []
for result in results:
tool_outputs.append(
{
"tool_call_id": result.tool_id,
"output": result.tool_output.content,
}
)
# Submit tool outputs to Azure
assert self._thread_id is not None, "Thread ID must be set."
assert self._run_id is not None, "Run ID must be set."
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Submitting tool call results for run_id={self._run_id} on thread_id={self._thread_id}: {tool_outputs}"
)
await self._client.agents.runs.submit_tool_outputs(
thread_id=self._thread_id, run_id=self._run_id, tool_outputs=tool_outputs
)
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Tool outputs submitted. Waiting for run to reach terminal state or next action required..."
)
# Wait for run to reach a terminal state or another action required
while True:
run: ThreadRun = await self._client.agents.runs.get(
thread_id=self._thread_id, run_id=self._run_id
)
if run.status not in ["queued", "in_progress", "requires_action"]:
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Run reached terminal state: {run.status}"
)
# Print detailed debug info if failed
if run.status == "failed":
print(
"[AzureFoundryWorkflowAgent][DEBUG] Run failed. Full run object:"
)
print(run)
# Try to print error fields if present
error_fields = [
"error",
"last_error",
"failure_reason",
"failure_message",
]
for field in error_fields:
if hasattr(run, field):
print(
f"[AzureFoundryWorkflowAgent][DEBUG] {field}: {getattr(run, field)}"
)
break
if run.status == "requires_action":
if self._verbose:
print(
f"[AzureFoundryWorkflowAgent] Run requires another action: {getattr(run, 'required_action', None)}"
)
break
await asyncio.sleep(self._run_retrieve_sleep_time)
tool_message = f"A tool call was executed : {results!s}"
await self._client.agents.messages.create(
thread_id=self._thread_id, role="assistant", content=tool_message
)
async def finalize(
self, ctx: Context, output: AgentOutput, memory: BaseMemory
) -> AgentOutput:
"""
Finalize the agent's execution (persist state, cleanup, etc).
For AzureFoundryWorkflowAgent, this can be a no-op or can persist any final state if needed.
"""
# Optionally, persist any final state to memory or context
# For now, just return the output as-is
return output
async def close(self):
"""
Close the underlying async Azure client session and credential.
"""
if self._verbose:
print(f"[AzureFoundryWorkflowAgent] Closing the session.")
await self._client.close()
await self._credential.close()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
await self.close()
def _from_azure_thread_message(self, thread_message: object) -> ChatMessage:
"""
Convert an Azure/OpenAI thread message to a LlamaIndex ChatMessage.
Supports text and image_url content blocks for multimodal support.
"""
from llama_index.core.base.llms.types import ChatMessage, TextBlock, ImageBlock
blocks = []
for t in getattr(thread_message, "content", []):
t_type = getattr(t, "type", None)
if t_type == "text":
text_val = getattr(getattr(t, "text", None), "value", "")
blocks.append(TextBlock(text=text_val))
elif t_type == "image_url":
url_val = getattr(getattr(t, "image_url", None), "url", None)
detail_val = getattr(getattr(t, "image_url", None), "detail", None)
if url_val:
blocks.append(ImageBlock(url=url_val, detail=detail_val))
# Compose content string for backward compatibility (concatenate text blocks)
content_str = " ".join([b.text for b in blocks if hasattr(b, "text")])
return ChatMessage(
role=getattr(thread_message, "role", ""),
content=content_str,
blocks=blocks,
additional_kwargs={
"thread_message": thread_message,
"thread_id": getattr(thread_message, "thread_id", None),
"assistant_id": getattr(thread_message, "assistant_id", None),
"id": getattr(thread_message, "id", None),
"metadata": getattr(thread_message, "metadata", None),
},
)
| AzureFoundryAgent |
python | openai__openai-python | src/openai/resources/beta/chatkit/threads.py | {
"start": 19067,
"end": 19556
} | class ____:
def __init__(self, threads: Threads) -> None:
self._threads = threads
self.retrieve = to_streamed_response_wrapper(
threads.retrieve,
)
self.list = to_streamed_response_wrapper(
threads.list,
)
self.delete = to_streamed_response_wrapper(
threads.delete,
)
self.list_items = to_streamed_response_wrapper(
threads.list_items,
)
| ThreadsWithStreamingResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 419529,
"end": 421644
} | class ____(sgqlc.types.Interface):
"""Represents a subject that can be reacted on."""
__schema__ = github_schema
__field_names__ = ("database_id", "id", "reaction_groups", "reactions", "viewer_can_react")
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
reaction_groups = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null("ReactionGroup")), graphql_name="reactionGroups")
"""A list of reactions grouped by content left on the subject."""
reactions = sgqlc.types.Field(
sgqlc.types.non_null("ReactionConnection"),
graphql_name="reactions",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
("before", sgqlc.types.Arg(String, graphql_name="before", default=None)),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
("content", sgqlc.types.Arg(ReactionContent, graphql_name="content", default=None)),
("order_by", sgqlc.types.Arg(ReactionOrder, graphql_name="orderBy", default=None)),
)
),
)
"""A list of Reactions left on the Issue.
Arguments:
* `after` (`String`): Returns the elements in the list that come
after the specified cursor.
* `before` (`String`): Returns the elements in the list that come
before the specified cursor.
* `first` (`Int`): Returns the first _n_ elements from the list.
* `last` (`Int`): Returns the last _n_ elements from the list.
* `content` (`ReactionContent`): Allows filtering Reactions by
emoji.
* `order_by` (`ReactionOrder`): Allows specifying the order in
which reactions are returned.
"""
viewer_can_react = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanReact")
"""Can user react to this subject"""
| Reactable |
python | getsentry__sentry | src/sentry/search/eap/types.py | {
"start": 2506,
"end": 2626
} | class ____(TypedDict):
name: str
type: Literal["string", "number"]
value: str | int | float
| TraceItemAttribute |
python | huggingface__transformers | src/transformers/models/beit/modeling_beit.py | {
"start": 29448,
"end": 32382
} | class ____(BeitPreTrainedModel):
def __init__(self, config: BeitConfig, add_pooling_layer: bool = True) -> None:
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self.embeddings = BeitEmbeddings(config)
self.encoder = BeitEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
self.layernorm = (
nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
)
self.pooler = BeitPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.patch_embeddings
@auto_docstring
def forward(
self,
pixel_values: torch.Tensor,
bool_masked_pos: Optional[torch.BoolTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
interpolate_pos_encoding: bool = False,
return_dict: Optional[bool] = None,
) -> Union[tuple, BeitModelOutputWithPooling]:
r"""
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
embedding_output, _ = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
resolution = pixel_values.shape[2:]
encoder_outputs = self.encoder(
embedding_output,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
resolution=resolution,
return_dict=return_dict,
interpolate_pos_encoding=interpolate_pos_encoding,
)
sequence_output = encoder_outputs[0]
sequence_output = self.layernorm(sequence_output)
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
return head_outputs + encoder_outputs[1:]
return BeitModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
| BeitModel |
python | mlflow__mlflow | tests/projects/test_databricks.py | {
"start": 16002,
"end": 18532
} | class ____:
def __init__(self, profile):
assert profile == "my-profile"
def get_config(self):
return DatabricksConfig.from_password("host", "user", "pass", insecure=False)
def test_databricks_http_request_integration():
"""Confirms that the databricks http request params can in fact be used as an HTTP request"""
def confirm_request_params(*args, **kwargs):
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Basic dXNlcjpwYXNz"
assert args == ("PUT", "host/clusters/list")
assert kwargs == {
"allow_redirects": True,
"headers": headers,
"verify": True,
"json": {"a": "b"},
"timeout": 120,
}
http_response = mock.MagicMock()
http_response.status_code = 200
http_response.text = '{"OK": "woo"}'
return http_response
with (
mock.patch("requests.Session.request", side_effect=confirm_request_params),
mock.patch(
"mlflow.utils.databricks_utils.get_databricks_host_creds",
return_value=MlflowHostCreds(
host="host", username="user", password="pass", ignore_tls_verification=False
),
),
):
response = DatabricksJobRunner(databricks_profile_uri=None)._databricks_api_request(
"/clusters/list", "PUT", json={"a": "b"}
)
assert json.loads(response.text) == {"OK": "woo"}
def test_run_databricks_failed():
text = '{"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "Node type not supported"}'
with (
mock.patch("mlflow.utils.databricks_utils.get_databricks_host_creds"),
mock.patch(
"mlflow.utils.rest_utils.http_request",
return_value=mock.Mock(text=text, status_code=400),
),
):
runner = DatabricksJobRunner(construct_db_uri_from_profile("profile"))
with pytest.raises(
MlflowException, match="RESOURCE_DOES_NOT_EXIST: Node type not supported"
):
runner._run_shell_command_job("/project", "command", {}, {})
def test_run_databricks_generates_valid_mlflow_run_cmd():
cmd = _get_cluster_mlflow_run_cmd(
project_dir="my_project_dir",
run_id="hi",
entry_point="main",
parameters={"a": "b"},
env_manager="conda",
)
assert cmd[0] == "mlflow"
with mock.patch("mlflow.projects.run"):
invoke_cli_runner(cli.cli, cmd[1:])
| MockProfileConfigProvider |
python | weaviate__weaviate-python-client | weaviate/gql/filter.py | {
"start": 19883,
"end": 32956
} | class ____(Filter):
"""Where filter class used to filter weaviate objects."""
def __init__(self, content: dict):
"""Initialize a Where filter class instance.
Args:
content: The content of the `where` filter clause.
Raises:
TypeError: If 'content' is not of type dict.
ValueError: If a mandatory key is missing in the filter content.
"""
super().__init__(content)
if "path" in self._content:
self.is_filter = True
self._parse_filter(self._content)
elif "operands" in self._content:
self.is_filter = False
self._parse_operator(self._content)
else:
raise ValueError(
f"Filter is missing required fields `path` or `operands`. Given: {self._content}"
)
def _parse_filter(self, content: dict) -> None:
"""Set filter fields for the Where filter.
Args:
content: The content of the `where` filter clause.
Raises:
ValueError: If 'content' is missing required fields.
"""
if "operator" not in content:
raise ValueError(f"Filter is missing required field `operator`. Given: {content}")
if content["operator"] not in WHERE_OPERATORS:
raise ValueError(
f"Operator {content['operator']} is not allowed. "
f"Allowed operators are: {', '.join(WHERE_OPERATORS)}"
)
self.path = dumps(content["path"])
self.operator = content["operator"]
self.value_type = _find_value_type(content)
self.value = content[self.value_type]
if self.operator == "WithinGeoRange" and self.value_type != "valueGeoRange":
raise ValueError(
f"Operator {self.operator} requires a value of type valueGeoRange. "
f"Given value type: {self.value_type}"
)
def _parse_operator(self, content: dict) -> None:
"""Set operator fields for the Where filter.
Args:
content: The content of the `where` filter clause.
Raises:
ValueError: If 'content' is missing required fields.
"""
if "operator" not in content:
raise ValueError(f"Filter is missing required field `operator`. Given: {content}")
if content["operator"] not in WHERE_OPERATORS:
raise ValueError(
f"Operator {content['operator']} is not allowed. "
f"Allowed operators are: {WHERE_OPERATORS}"
)
_content = deepcopy(content)
self.operator = _content["operator"]
self.operands = []
for operand in _content["operands"]:
self.operands.append(Where(operand))
def __str__(self) -> str:
if self.is_filter:
gql = f"where: {{path: {self.path} operator: {self.operator} {_convert_value_type(self.value_type)}: "
if self.value_type in [
"valueInt",
"valueNumber",
"valueIntArray",
"valueNumberArray",
"valueIntList",
"valueNumberList",
]:
if self.value_type in [
"valueIntList",
"valueNumberList",
"valueIntList",
"valueNumberList",
]:
_check_is_list(self.value, self.value_type)
gql += f"{self.value}}}"
elif self.value_type in [
"valueText",
"valueString",
"valueTextList",
"valueStringList",
"valueTextArray",
"valueStringArray",
]:
if self.value_type in [
"valueTextList",
"valueStringList",
"valueTextArray",
"valueStringArray",
]:
_check_is_list(self.value, self.value_type)
if isinstance(self.value, list):
val = [_sanitize_str(v) for v in self.value]
gql += f"{_render_list(val)}}}"
else:
gql += f"{_sanitize_str(self.value)}}}"
elif self.value_type in [
"valueBoolean",
"valueBooleanArray",
"valueBooleanList",
]:
if self.value_type in ["valueBooleanArray", "valueBooleanList"]:
_check_is_list(self.value, self.value_type)
if isinstance(self.value, list):
gql += f"{_render_list(self.value)}}}"
else:
gql += f"{_bool_to_str(self.value)}}}"
elif self.value_type in ["valueDateArray", "valueDateList"]:
_check_is_list(self.value, self.value_type)
gql += f"{_render_list_date(self.value)}}}"
elif self.value_type == "valueGeoRange":
_check_is_not_list(self.value, self.value_type)
gql += f"{_geo_range_to_str(self.value)}}}"
else:
gql += f'"{self.value}"}}'
return gql + " "
operands_str = []
for operand in self.operands:
# remove the `where: ` from the operands and the last space
operands_str.append(str(operand)[7:-1])
operands = ", ".join(operands_str)
return f"where: {{operator: {self.operator} operands: [{operands}]}} "
def _convert_value_type(_type: str) -> str:
"""Convert the value type to match `json` formatting required by the Weaviate-defined GraphQL endpoints.
NOTE: This is crucially different to the Batch REST endpoints wherein
the where filter is also used.
Args:
_type: The Python-defined type to be converted.
Returns:
The string interpretation of the type in Weaviate-defined `json` format.
"""
if _type == "valueTextArray" or _type == "valueTextList":
return "valueText"
elif _type == "valueStringArray" or _type == "valueStringList":
return "valueString"
elif _type == "valueIntArray" or _type == "valueIntList":
return "valueInt"
elif _type == "valueNumberArray" or _type == "valueNumberList":
return "valueNumber"
elif _type == "valueBooleanArray" or _type == "valueBooleanList":
return "valueBoolean"
elif _type == "valueDateArray" or _type == "valueDateList":
return "valueDate"
else:
return _type
def _render_list(input_list: list) -> str:
"""Convert a list of values to string (lowercased) to match `json` formatting.
Args:
input_list: The value to be converted
Returns:
The string interpretation of the value in `json` format.
"""
str_list = ",".join(str(item) for item in input_list)
return f"[{str_list}]"
def _render_list_date(input_list: list) -> str:
str_list = ",".join('"' + str(item) + '"' for item in input_list)
return f"[{str_list}]"
def _check_is_list(value: Any, _type: str) -> None:
"""Checks whether the provided value is a list to match the given `value_type`.
Args:
value: The value to be checked.
_type: The type to be checked against.
Raises:
TypeError: If the value is not a list.
"""
if not isinstance(value, list):
raise TypeError(
f"Must provide a list when constructing where filter for {_type} with {value}"
)
def _check_is_not_list(value: Any, _type: str) -> None:
"""Checks whether the provided value is a list to match the given `value_type`.
Args:
value: The value to be checked.
_type: The type to be checked against.
Raises:
TypeError: If the value is a list.
"""
if isinstance(value, list):
raise TypeError(
f"Cannot provide a list when constructing where filter for {_type} with {value}"
)
def _geo_range_to_str(value: dict) -> str:
"""Convert the valueGeoRange object to match `json` formatting.
Args:
value: The value to be converted.
Returns:
The string interpretation of the value in `json` format.
"""
latitude = value["geoCoordinates"]["latitude"]
longitude = value["geoCoordinates"]["longitude"]
distance = value["distance"]["max"]
return f"{{ geoCoordinates: {{ latitude: {latitude} longitude: {longitude} }} distance: {{ max: {distance} }}}}"
def _bool_to_str(value: bool) -> str:
"""Convert a bool value to string (lowercased) to match `json` formatting.
Args:
value: The value to be converted
Returns:
The string interpretation of the value in `json` format.
"""
if value is True:
return "true"
return "false"
def _check_direction_clause(direction: dict) -> None:
"""Validate the direction sub clause.
Args:
direction: A sub clause of the Explore filter.
Raises:
TypeError: If 'direction' is not a dict.
TypeError: If the value of the "force" key is not float.
ValueError: If no "force" key in the 'direction'.
"""
_check_type(var_name="moveXXX", value=direction, dtype=dict)
if ("concepts" not in direction) and ("objects" not in direction):
raise ValueError("The 'move' clause should contain `concepts` OR/AND `objects`!")
if "concepts" in direction:
_check_concept(direction)
if "objects" in direction:
_check_objects(direction)
if "force" not in direction:
raise ValueError("'move' clause needs to state a 'force'")
_check_type(var_name="force", value=direction["force"], dtype=float)
def _check_concept(content: dict) -> None:
"""Validate the concept sub clause.
Args:
content: An Explore (sub) clause to check for 'concepts'.
Raises:
ValueError: If no "concepts" key in the 'content' dict.
TypeError: If the value of the "concepts" is of wrong type.
"""
if "concepts" not in content:
raise ValueError("No concepts in content")
_check_type(
var_name="concepts",
value=content["concepts"],
dtype=(list, str),
)
if isinstance(content["concepts"], str):
content["concepts"] = [content["concepts"]]
def _check_objects(content: dict) -> None:
"""Validate the `objects` sub clause of the `move` clause.
Args:
content: An Explore (sub) clause to check for 'objects'.
Raises:
ValueError: If no "concepts" key in the 'content' dict.
TypeError: If the value of the "concepts" is of wrong type.
"""
_check_type(var_name="objects", value=content["objects"], dtype=(list, dict))
if isinstance(content["objects"], dict):
content["objects"] = [content["objects"]]
if len(content["objects"]) == 0:
raise ValueError("'moveXXX' clause specifies 'objects' but no value provided.")
for obj in content["objects"]:
if len(obj) != 1 or ("id" not in obj and "beacon" not in obj):
raise ValueError(
"Each object from the `move` clause should have ONLY `id` OR `beacon`!"
)
def _check_type(var_name: str, value: Any, dtype: Union[Tuple[type, type], type]) -> None:
"""Check key-value type.
Args:
var_name: The variable name for which to check the type (used for error message)!
value: The value for which to check the type.
dtype: The expected data type of the `value`.
Raises:
TypeError: If the `value` type does not match the expected `dtype`.
"""
if not isinstance(value, dtype):
raise TypeError(
f"'{var_name}' key-value is expected to be of type {dtype} but is {type(value)}!"
)
def _find_value_type(content: dict) -> str:
"""Find the correct type of the content.
Args:
content: The content for which to find the appropriate data type.
Returns:
The correct data type.
Raises:
ValueError: If missing required fields.
"""
value_type = ALL_VALUE_TYPES & set(content.keys())
if len(value_type) == 0:
raise ValueError(
f"'value<TYPE>' field is either missing or incorrect: {content}. Valid values are: {VALUE_TYPES}."
)
if len(value_type) != 1:
raise ValueError(f"Multiple fields 'value<TYPE>' are not supported: {content}")
return value_type.pop()
def _move_clause_objects_to_str(objects: list) -> str:
"""Creates the Weaviate `moveTo`/`moveAwayFrom` clause given the list of objects.
Args:
objects: The list of objects to be used for the `moveTo`/`moveAwayFrom` clause.
Returns:
The `moveTo`/`moveAwayFrom` clause as a string.
"""
to_return = " objects: ["
for obj in objects:
if "id" in obj:
id_beacon = "id"
else:
id_beacon = "beacon"
to_return += f"{{{id_beacon}: {dumps(obj[id_beacon])}}} "
return to_return + "]"
| Where |
python | numba__numba | numba/core/ir.py | {
"start": 28411,
"end": 28746
} | class ____(Inst):
def __init__(self, value, loc, index):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.value = value
self.loc = loc
self.index = index
def __str__(self):
return 'yield %s' % (self.value,)
def list_vars(self):
return [self.value]
| Yield |
python | scipy__scipy | scipy/signal/tests/test_dltisys.py | {
"start": 11554,
"end": 12602
} | class ____:
def test_initialization(self):
# Check that all initializations work
dt = 0.05
StateSpace(1, 1, 1, 1, dt=dt)
StateSpace([1], [2], [3], [4], dt=dt)
StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
np.array([[1, 0]]), np.array([[0]]), dt=dt)
StateSpace(1, 1, 1, 1, dt=True)
def test_conversion(self):
# Check the conversion functions
s = StateSpace(1, 2, 3, 4, dt=0.05)
assert isinstance(s.to_ss(), StateSpace)
assert isinstance(s.to_tf(), TransferFunction)
assert isinstance(s.to_zpk(), ZerosPolesGain)
# Make sure copies work
assert StateSpace(s) is not s
assert s.to_ss() is not s
def test_properties(self):
# Test setters/getters for cross class properties.
# This implicitly tests to_tf() and to_zpk()
# Getters
s = StateSpace(1, 1, 1, 1, dt=0.05)
xp_assert_equal(s.poles, [1.])
xp_assert_equal(s.zeros, [0.])
| TestStateSpaceDisc |
python | kamyu104__LeetCode-Solutions | Python/find-right-interval.py | {
"start": 49,
"end": 543
} | class ____(object):
def findRightInterval(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[int]
"""
sorted_intervals = sorted((interval.start, i) for i, interval in enumerate(intervals))
result = []
for interval in intervals:
idx = bisect.bisect_left(sorted_intervals, (interval.end,))
result.append(sorted_intervals[idx][1] if idx < len(sorted_intervals) else -1)
return result
| Solution |
python | walkccc__LeetCode | solutions/919. Complete Binary Tree Inserter/919.py | {
"start": 0,
"end": 544
} | class ____:
def __init__(self, root: TreeNode | None):
self.tree = [root]
for node in self.tree:
if node.left:
self.tree.append(node.left)
if node.right:
self.tree.append(node.right)
def insert(self, v: int) -> int:
n = len(self.tree)
self.tree.append(TreeNode(v))
parent = self.tree[(n - 1) // 2]
if n % 2 == 1:
parent.left = self.tree[-1]
else:
parent.right = self.tree[-1]
return parent.val
def get_root(self) -> TreeNode | None:
return self.tree[0]
| CBTInserter |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 2959,
"end": 7954
} | class ____(nn.Module):
"""
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
"""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
if config.emb_layer_norm_before:
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
else:
self.layer_norm = None
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
self.padding_idx = config.pad_token_id
if self.position_embedding_type == "absolute":
self.position_embeddings = nn.Embedding(
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
)
self.token_dropout = config.token_dropout
self.mask_token_id = config.mask_token_id
# remove the position_ids in EsmEmbeddings
self.position_ids = None
def forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
inputs_embeds=None,
):
if position_ids is None:
if input_ids is not None:
# Create the position ids from the input token ids. Any padded tokens remain padded.
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
else:
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
# Note that if we want to support EVOLLA_SA_PROT-1 (not 1b!) in future then we need to support an
# embedding_scale factor here.
embeddings = inputs_embeds
# Matt: EVOLLA_SA_PROT has the option to handle masking in MLM in a slightly unusual way. If the token_dropout
# flag is False then it is handled in the same was as BERT/RoBERTa. If it is set to True, however,
# masked tokens are treated as if they were selected for input dropout and zeroed out.
# This "mask-dropout" is compensated for when masked tokens are not present, by scaling embeddings by
# a factor of (fraction of unmasked tokens during training) / (fraction of unmasked tokens in sample).
# This is analogous to the way that dropout layers scale down outputs during evaluation when not
# actually dropping out values (or, equivalently, scale up their un-dropped outputs in training).
if self.token_dropout and input_ids is not None:
embeddings = embeddings.masked_fill((input_ids == self.mask_token_id).unsqueeze(-1), 0.0)
mask_ratio_train = 0.15 * 0.8 # Hardcoded as the ratio used in all EVOLLA_SA_PROT model training runs
src_lengths = attention_mask.sum(-1) if attention_mask is not None else input_ids.shape[1]
mask_ratio_observed = (input_ids == self.mask_token_id).sum(-1).float() / src_lengths
embeddings = (embeddings * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]).to(
embeddings.dtype
)
if self.position_embedding_type == "absolute":
position_embeddings = self.position_embeddings(position_ids)
embeddings = embeddings + position_embeddings
if self.layer_norm is not None:
embeddings = self.layer_norm(embeddings)
if attention_mask is not None:
embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(embeddings.dtype)
# Matt: I think this line was copied incorrectly from BERT, disabling it for now.
# embeddings = self.dropout(embeddings)
return embeddings
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
"""
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
Args:
inputs_embeds: torch.Tensor
Returns: torch.Tensor
"""
input_shape = inputs_embeds.size()[:-1]
sequence_length = input_shape[1]
position_ids = torch.arange(
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
)
return position_ids.unsqueeze(0).expand(input_shape)
def rotate_half_esm(x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb_esm(x, cos, sin):
cos = cos[:, :, : x.shape[-2], :]
sin = sin[:, :, : x.shape[-2], :]
return (x * cos) + (rotate_half_esm(x) * sin)
| EvollaSaProtEmbeddings |
python | uqfoundation__dill | dill/tests/test_recursive.py | {
"start": 864,
"end": 946
} | class ____(object):
def __init__(self):
super(obj1, self).__init__()
| obj1 |
python | kamyu104__LeetCode-Solutions | Python/longest-common-suffix-queries.py | {
"start": 46,
"end": 1544
} | class ____(object):
def stringIndices(self, wordsContainer, wordsQuery):
"""
:type wordsContainer: List[str]
:type wordsQuery: List[str]
:rtype: List[int]
"""
INF = float("INF")
class Trie(object):
def __init__(self):
self.__nodes = []
self.__mns = []
self.__new_node()
def __new_node(self):
self.__nodes.append([-1]*26)
self.__mns.append((INF, INF))
return len(self.__nodes)-1
def add(self, i, w):
curr = 0
self.__mns[curr] = min(self.__mns[curr], (len(w), i))
for c in reversed(w):
x = ord(c)-ord('a')
if self.__nodes[curr][x] == -1:
self.__nodes[curr][x] = self.__new_node()
curr = self.__nodes[curr][x]
self.__mns[curr] = min(self.__mns[curr], (len(w), i))
def query(self, w):
curr = 0
for c in reversed(w):
x = ord(c)-ord('a')
if self.__nodes[curr][x] == -1:
break
curr = self.__nodes[curr][x]
return self.__mns[curr][1]
trie = Trie()
for i, w in enumerate(wordsContainer):
trie.add(i, w)
return [trie.query(w) for w in wordsQuery]
| Solution |
python | getsentry__sentry | src/sentry/issues/endpoints/group_similar_issues_embeddings.py | {
"start": 1317,
"end": 1442
} | class ____(TypedDict):
exception: float
shouldBeGrouped: str
@region_silo_endpoint
| FormattedSimilarIssuesEmbeddingsData |
python | realpython__materials | python-selenium/src/bandcamp/web/base.py | {
"start": 311,
"end": 438
} | class ____:
album: str
artist: str
genre: str
url: str
def __str__(self):
return pformat(self)
| Track |
python | wandb__wandb | wandb/sdk/data_types/trace_tree.py | {
"start": 938,
"end": 1116
} | class ____(str, Enum):
LLM = "LLM"
CHAIN = "CHAIN"
AGENT = "AGENT"
TOOL = "TOOL"
def __str__(self) -> str:
return str(self.value)
@dataclass()
| SpanKind |
python | Netflix__metaflow | metaflow/packaging_sys/backend.py | {
"start": 111,
"end": 3534
} | class ____(ABC):
_mappings = {}
type = "none"
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls.type in cls._mappings:
raise ValueError(f"PackagingBackend {cls.type} already exists")
cls._mappings[cls.type] = cls
@classmethod
def get_backend(cls, name: str) -> "PackagingBackend":
if name not in cls._mappings:
raise ValueError(f"PackagingBackend {name} not found")
return cls._mappings[name]
@classmethod
def backend_type(cls) -> str:
return cls.type
@classmethod
@abstractmethod
def get_extract_commands(cls, archive_name: str, dest_dir: str) -> List[str]:
pass
def __init__(self):
self._archive = None
@abstractmethod
def create(self) -> "PackagingBackend":
pass
@abstractmethod
def add_file(self, filename: str, arcname: Optional[str] = None):
pass
@abstractmethod
def add_data(self, data: BytesIO, arcname: str):
pass
@abstractmethod
def close(self):
pass
@abstractmethod
def get_blob(self) -> Optional[Union[bytes, bytearray]]:
pass
@classmethod
@abstractmethod
def cls_open(cls, content: IO[bytes]) -> Any:
"""Open the archive from the given content."""
pass
@classmethod
@abstractmethod
def cls_member_name(cls, member: Union[Any, str]) -> str:
"""
Returns the name of the member as a string.
This is used to ensure consistent naming across different archive formats.
"""
pass
@classmethod
@abstractmethod
def cls_has_member(cls, archive: Any, name: str) -> bool:
pass
@classmethod
@abstractmethod
def cls_get_member(cls, archive: Any, name: str) -> Optional[bytes]:
pass
@classmethod
@abstractmethod
def cls_extract_members(
cls,
archive: Any,
members: Optional[List[Any]] = None,
dest_dir: str = ".",
) -> None:
pass
@classmethod
@abstractmethod
def cls_list_names(cls, archive: Any) -> Optional[List[str]]:
pass
@classmethod
@abstractmethod
def cls_list_members(cls, archive: Any) -> Optional[List[Any]]:
"""List all members in the archive."""
pass
def has_member(self, name: str) -> bool:
if self._archive:
return self.cls_has_member(self._archive, name)
raise ValueError("Cannot check for member in an uncreated archive")
def get_member(self, name: str) -> Optional[bytes]:
if self._archive:
return self.cls_get_member(self._archive, name)
raise ValueError("Cannot get member from an uncreated archive")
def extract_members(
self, members: Optional[List[Any]] = None, dest_dir: str = "."
) -> None:
if self._archive:
self.cls_extract_members(self._archive, members, dest_dir)
else:
raise ValueError("Cannot extract from an uncreated archive")
def list_names(self) -> Optional[List[str]]:
if self._archive:
return self.cls_list_names(self._archive)
raise ValueError("Cannot list names from an uncreated archive")
def __enter__(self):
self.create()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
| PackagingBackend |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 155980,
"end": 161018
} | class ____(Response):
"""
Response of projects.validate_delete endpoint.
:param tasks: The total number of tasks under the project and all its children
:type tasks: int
:param non_archived_tasks: The total number of non-archived tasks under the
project and all its children
:type non_archived_tasks: int
:param models: The total number of models under the project and all its
children
:type models: int
:param non_archived_models: The total number of non-archived models under the
project and all its children
:type non_archived_models: int
"""
_service = "projects"
_action = "validate_delete"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"models": {
"description": "The total number of models under the project and all its children",
"type": ["integer", "null"],
},
"non_archived_models": {
"description": "The total number of non-archived models under the project and all its children",
"type": ["integer", "null"],
},
"non_archived_tasks": {
"description": "The total number of non-archived tasks under the project and all its children",
"type": ["integer", "null"],
},
"tasks": {
"description": "The total number of tasks under the project and all its children",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
tasks: Optional[int] = None,
non_archived_tasks: Optional[int] = None,
models: Optional[int] = None,
non_archived_models: Optional[int] = None,
**kwargs: Any
) -> None:
super(ValidateDeleteResponse, self).__init__(**kwargs)
self.tasks = tasks
self.non_archived_tasks = non_archived_tasks
self.models = models
self.non_archived_models = non_archived_models
@schema_property("tasks")
def tasks(self) -> Optional[int]:
return self._property_tasks
@tasks.setter
def tasks(self, value: Optional[int]) -> None:
if value is None:
self._property_tasks = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "tasks", six.integer_types)
self._property_tasks = value
@schema_property("non_archived_tasks")
def non_archived_tasks(self) -> Optional[int]:
return self._property_non_archived_tasks
@non_archived_tasks.setter
def non_archived_tasks(self, value: Optional[int]) -> None:
if value is None:
self._property_non_archived_tasks = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "non_archived_tasks", six.integer_types)
self._property_non_archived_tasks = value
@schema_property("models")
def models(self) -> Optional[int]:
return self._property_models
@models.setter
def models(self, value: Optional[int]) -> None:
if value is None:
self._property_models = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "models", six.integer_types)
self._property_models = value
@schema_property("non_archived_models")
def non_archived_models(self) -> Optional[int]:
return self._property_non_archived_models
@non_archived_models.setter
def non_archived_models(self, value: Optional[int]) -> None:
if value is None:
self._property_non_archived_models = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "non_archived_models", six.integer_types)
self._property_non_archived_models = value
response_mapping = {
CreateRequest: CreateResponse,
GetByIdRequest: GetByIdResponse,
GetAllRequest: GetAllResponse,
UpdateRequest: UpdateResponse,
MoveRequest: MoveResponse,
MergeRequest: MergeResponse,
ValidateDeleteRequest: ValidateDeleteResponse,
DeleteRequest: DeleteResponse,
GetUniqueMetricVariantsRequest: GetUniqueMetricVariantsResponse,
GetHyperparamValuesRequest: GetHyperparamValuesResponse,
GetHyperParametersRequest: GetHyperParametersResponse,
GetModelMetadataValuesRequest: GetModelMetadataValuesResponse,
GetModelMetadataKeysRequest: GetModelMetadataKeysResponse,
GetProjectTagsRequest: GetProjectTagsResponse,
GetTaskTagsRequest: GetTaskTagsResponse,
GetModelTagsRequest: GetModelTagsResponse,
MakePublicRequest: MakePublicResponse,
MakePrivateRequest: MakePrivateResponse,
GetTaskParentsRequest: GetTaskParentsResponse,
}
| ValidateDeleteResponse |
python | ansible__ansible | test/lib/ansible_test/_internal/diff.py | {
"start": 3306,
"end": 7311
} | class ____:
"""Parse diff lines."""
def __init__(self, lines: list[str]) -> None:
self.lines = lines
self.files: list[FileDiff] = []
self.action = self.process_start
self.line_number = 0
self.previous_line: t.Optional[str] = None
self.line: t.Optional[str] = None
self.file: t.Optional[FileDiff] = None
for self.line in self.lines:
self.line_number += 1
try:
self.action()
except Exception as ex:
message = textwrap.dedent("""
%s
Line: %d
Previous: %s
Current: %s
%s
""").strip() % (
ex,
self.line_number,
self.previous_line or '',
self.line or '',
traceback.format_exc(),
)
raise ApplicationError(message.strip()) from None
self.previous_line = self.line
self.complete_file()
def process_start(self) -> None:
"""Process a diff start line."""
self.complete_file()
match = re.search(r'^diff --git "?(?:a/)?(?P<old_path>.*)"? "?(?:b/)?(?P<new_path>.*)"?$', self.line)
if not match:
raise Exception('Unexpected diff start line.')
self.file = FileDiff(match.group('old_path'), match.group('new_path'))
self.action = self.process_continue
def process_range(self) -> None:
"""Process a diff range line."""
match = re.search(r'^@@ -((?P<old_start>[0-9]+),)?(?P<old_count>[0-9]+) \+((?P<new_start>[0-9]+),)?(?P<new_count>[0-9]+) @@', self.line)
if not match:
raise Exception('Unexpected diff range line.')
self.file.old.set_start(int(match.group('old_start') or 1), int(match.group('old_count')))
self.file.new.set_start(int(match.group('new_start') or 1), int(match.group('new_count')))
self.action = self.process_content
def process_continue(self) -> None:
"""Process a diff start, range or header line."""
if self.line.startswith('diff '):
self.process_start()
elif self.line.startswith('@@ '):
self.process_range()
else:
self.process_header()
def process_header(self) -> None:
"""Process a diff header line."""
if self.line.startswith('Binary files '):
self.file.binary = True
elif self.line == '--- /dev/null':
self.file.old.exists = False
elif self.line == '+++ /dev/null':
self.file.new.exists = False
else:
self.file.append_header(self.line)
def process_content(self) -> None:
"""Process a diff content line."""
if self.line == r'\ No newline at end of file':
if self.previous_line.startswith(' '):
self.file.old.eof_newline = False
self.file.new.eof_newline = False
elif self.previous_line.startswith('-'):
self.file.old.eof_newline = False
elif self.previous_line.startswith('+'):
self.file.new.eof_newline = False
else:
raise Exception('Unexpected previous diff content line.')
return
if self.file.is_complete:
self.process_continue()
return
if self.line.startswith(' '):
self.file.old.append(self.line)
self.file.new.append(self.line)
elif self.line.startswith('-'):
self.file.old.append(self.line)
elif self.line.startswith('+'):
self.file.new.append(self.line)
else:
raise Exception('Unexpected diff content line.')
def complete_file(self) -> None:
"""Complete processing of the current file, if any."""
if not self.file:
return
self.files.append(self.file)
| DiffParser |
python | astropy__astropy | astropy/io/ascii/ipac.py | {
"start": 11568,
"end": 11687
} | class ____(fixedwidth.FixedWidthSplitter):
delimiter = " "
delimiter_pad = ""
bookend = True
| IpacDataSplitter |
python | coleifer__peewee | tests/db_tests.py | {
"start": 16738,
"end": 16922
} | class ____(TestModel):
first = CharField()
last = CharField()
email = CharField()
class Meta:
indexes = (
(('last', 'first'), False),
)
| Person |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 44469,
"end": 44832
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("owner_id", "client_mutation_id")
owner_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="ownerId")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| AbortQueuedMigrationsInput |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/context.py | {
"start": 20689,
"end": 23657
} | class ____(Sequence["AssetEventResult"]):
_after: str | datetime | None
_before: str | datetime | None
_ascending: bool
_limit: int | None
_asset_name: str | None
_asset_uri: str | None
_alias_name: str | None
def __init__(
self, asset_name: str | None = None, asset_uri: str | None = None, alias_name: str | None = None
):
self._asset_name = asset_name
self._asset_uri = asset_uri
self._alias_name = alias_name
self._after = None
self._before = None
self._ascending = True
self._limit = None
def after(self, after: str) -> Self:
self._after = after
self._reset_cache()
return self
def before(self, before: str) -> Self:
self._before = before
self._reset_cache()
return self
def ascending(self, ascending: bool = True) -> Self:
self._ascending = ascending
self._reset_cache()
return self
def limit(self, limit: int) -> Self:
self._limit = limit
self._reset_cache()
return self
@functools.cached_property
def _asset_events(self) -> list[AssetEventResult]:
from airflow.sdk.execution_time.comms import (
ErrorResponse,
GetAssetEventByAsset,
GetAssetEventByAssetAlias,
ToSupervisor,
)
from airflow.sdk.execution_time.task_runner import SUPERVISOR_COMMS
query_dict: dict[str, Any] = {
"after": self._after,
"before": self._before,
"ascending": self._ascending,
"limit": self._limit,
}
msg: ToSupervisor
if self._alias_name is not None:
msg = GetAssetEventByAssetAlias(alias_name=self._alias_name, **query_dict)
else:
if self._asset_name is None and self._asset_uri is None:
raise ValueError("Either asset_name or asset_uri must be provided")
msg = GetAssetEventByAsset(name=self._asset_name, uri=self._asset_uri, **query_dict)
resp = SUPERVISOR_COMMS.send(msg)
if isinstance(resp, ErrorResponse):
raise AirflowRuntimeError(resp)
if TYPE_CHECKING:
assert isinstance(resp, AssetEventsResult)
return list(resp.iter_asset_event_results())
def _reset_cache(self) -> None:
try:
del self._asset_events
except AttributeError:
pass
def __iter__(self) -> Iterator[AssetEventResult]:
return iter(self._asset_events)
def __len__(self) -> int:
return len(self._asset_events)
@overload
def __getitem__(self, key: int) -> AssetEventResult: ...
@overload
def __getitem__(self, key: slice) -> Sequence[AssetEventResult]: ...
def __getitem__(self, key: int | slice) -> AssetEventResult | Sequence[AssetEventResult]:
return self._asset_events[key]
@attrs.define(init=False)
| InletEventsAccessor |
python | openai__openai-python | src/openai/types/moderation_image_url_input_param.py | {
"start": 375,
"end": 622
} | class ____(TypedDict, total=False):
image_url: Required[ImageURL]
"""Contains either an image URL or a data URL for a base64 encoded image."""
type: Required[Literal["image_url"]]
"""Always `image_url`."""
| ModerationImageURLInputParam |
python | plotly__plotly.py | plotly/graph_objs/layout/_coloraxis.py | {
"start": 235,
"end": 14577
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.coloraxis"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"colorbar",
"colorscale",
"reversescale",
"showscale",
}
@property
def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`colorscale`. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette will be chosen
according to whether numbers in the `color` array are all
positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["autocolorscale"]
@autocolorscale.setter
def autocolorscale(self, val):
self["autocolorscale"] = val
@property
def cauto(self):
"""
Determines whether or not the color domain is computed with
respect to the input data (here corresponding trace color
array(s)) or the bounds set in `cmin` and `cmax` Defaults to
`false` when `cmin` and `cmax` are set by the user.
The 'cauto' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["cauto"]
@cauto.setter
def cauto(self, val):
self["cauto"] = val
@property
def cmax(self):
"""
Sets the upper bound of the color domain. Value should have the
same units as corresponding trace color array(s) and if set,
`cmin` must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmax"]
@cmax.setter
def cmax(self, val):
self["cmax"] = val
@property
def cmid(self):
"""
Sets the mid-point of the color domain by scaling `cmin` and/or
`cmax` to be equidistant to this point. Value should have the
same units as corresponding trace color array(s). Has no effect
when `cauto` is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmid"]
@cmid.setter
def cmid(self, val):
self["cmid"] = val
@property
def cmin(self):
"""
Sets the lower bound of the color domain. Value should have the
same units as corresponding trace color array(s) and if set,
`cmax` must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmin"]
@cmin.setter
def cmin(self, val):
self["cmin"] = val
@property
def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.coloraxis.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Returns
-------
plotly.graph_objs.layout.coloraxis.ColorBar
"""
return self["colorbar"]
@colorbar.setter
def colorbar(self, val):
self["colorbar"] = val
@property
def colorscale(self):
"""
Sets the colorscale. The colorscale must be an array containing
arrays mapping a normalized value to an rgb, rgba, hex, hsl,
hsv, or named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the
bounds of the colorscale in color space, use `cmin` and `cmax`.
Alternatively, `colorscale` may be a palette name string of the
following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis,
YlGnBu,YlOrRd.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl',
'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn',
'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu',
'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar',
'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn',
'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid',
'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr',
'ylorrd'].
Appending '_r' to a named colorscale reverses it.
Returns
-------
str
"""
return self["colorscale"]
@colorscale.setter
def colorscale(self, val):
self["colorscale"] = val
@property
def reversescale(self):
"""
Reverses the color mapping if true. If true, `cmin` will
correspond to the last color in the array and `cmax` will
correspond to the first color.
The 'reversescale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["reversescale"]
@reversescale.setter
def reversescale(self, val):
self["reversescale"] = val
@property
def showscale(self):
"""
Determines whether or not a colorbar is displayed for this
trace.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showscale"]
@showscale.setter
def showscale(self, val):
self["showscale"] = val
@property
def _prop_descriptions(self):
return """\
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`colorscale`. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette will be
chosen according to whether numbers in the `color`
array are all positive, all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here corresponding
trace color array(s)) or the bounds set in `cmin` and
`cmax` Defaults to `false` when `cmin` and `cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Value should
have the same units as corresponding trace color
array(s) and if set, `cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`cmin` and/or `cmax` to be equidistant to this point.
Value should have the same units as corresponding trace
color array(s). Has no effect when `cauto` is `false`.
cmin
Sets the lower bound of the color domain. Value should
have the same units as corresponding trace color
array(s) and if set, `cmax` must be set as well.
colorbar
:class:`plotly.graph_objects.layout.coloraxis.ColorBar`
instance or dict with compatible properties
colorscale
Sets the colorscale. The colorscale must be an array
containing arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At minimum,
a mapping for the lowest (0) and highest (1) values are
required. For example, `[[0, 'rgb(0,0,255)'], [1,
'rgb(255,0,0)']]`. To control the bounds of the
colorscale in color space, use `cmin` and `cmax`.
Alternatively, `colorscale` may be a palette name
string of the following list: Blackbody,Bluered,Blues,C
ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl
and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd.
reversescale
Reverses the color mapping if true. If true, `cmin`
will correspond to the last color in the array and
`cmax` will correspond to the first color.
showscale
Determines whether or not a colorbar is displayed for
this trace.
"""
def __init__(
self,
arg=None,
autocolorscale=None,
cauto=None,
cmax=None,
cmid=None,
cmin=None,
colorbar=None,
colorscale=None,
reversescale=None,
showscale=None,
**kwargs,
):
"""
Construct a new Coloraxis object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Coloraxis`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`colorscale`. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette will be
chosen according to whether numbers in the `color`
array are all positive, all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here corresponding
trace color array(s)) or the bounds set in `cmin` and
`cmax` Defaults to `false` when `cmin` and `cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Value should
have the same units as corresponding trace color
array(s) and if set, `cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`cmin` and/or `cmax` to be equidistant to this point.
Value should have the same units as corresponding trace
color array(s). Has no effect when `cauto` is `false`.
cmin
Sets the lower bound of the color domain. Value should
have the same units as corresponding trace color
array(s) and if set, `cmax` must be set as well.
colorbar
:class:`plotly.graph_objects.layout.coloraxis.ColorBar`
instance or dict with compatible properties
colorscale
Sets the colorscale. The colorscale must be an array
containing arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At minimum,
a mapping for the lowest (0) and highest (1) values are
required. For example, `[[0, 'rgb(0,0,255)'], [1,
'rgb(255,0,0)']]`. To control the bounds of the
colorscale in color space, use `cmin` and `cmax`.
Alternatively, `colorscale` may be a palette name
string of the following list: Blackbody,Bluered,Blues,C
ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl
and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd.
reversescale
Reverses the color mapping if true. If true, `cmin`
will correspond to the last color in the array and
`cmax` will correspond to the first color.
showscale
Determines whether or not a colorbar is displayed for
this trace.
Returns
-------
Coloraxis
"""
super().__init__("coloraxis")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.Coloraxis
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Coloraxis`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("autocolorscale", arg, autocolorscale)
self._set_property("cauto", arg, cauto)
self._set_property("cmax", arg, cmax)
self._set_property("cmid", arg, cmid)
self._set_property("cmin", arg, cmin)
self._set_property("colorbar", arg, colorbar)
self._set_property("colorscale", arg, colorscale)
self._set_property("reversescale", arg, reversescale)
self._set_property("showscale", arg, showscale)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Coloraxis |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 61476,
"end": 63771
} | class ____(Request):
"""
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
:param count: Number of positions in the queue to move the task forward
relative to the current position. Optional, the default value is 1.
:type count: int
"""
_service = "queues"
_action = "move_task_backward"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"count": {
"description": "Number of positions in the queue to move the task forward relative to the current position. Optional, the default value is 1.",
"type": "integer",
},
"queue": {"description": "Queue id", "type": "string"},
"task": {"description": "Task id", "type": "string"},
},
"required": ["queue", "task"],
"type": "object",
}
def __init__(self, queue: str, task: str, count: Optional[int] = None, **kwargs: Any) -> None:
super(MoveTaskBackwardRequest, self).__init__(**kwargs)
self.queue = queue
self.task = task
self.count = count
@schema_property("queue")
def queue(self) -> str:
return self._property_queue
@queue.setter
def queue(self, value: str) -> None:
if value is None:
self._property_queue = None
return
self.assert_isinstance(value, "queue", six.string_types)
self._property_queue = value
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("count")
def count(self) -> Optional[int]:
return self._property_count
@count.setter
def count(self, value: Optional[int]) -> None:
if value is None:
self._property_count = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "count", six.integer_types)
self._property_count = value
| MoveTaskBackwardRequest |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_L.py | {
"start": 87,
"end": 1617
} | class ____(Benchmark):
r"""
Langermann objective function.
This class defines the Langermann [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Langermann}}(x) = - \sum_{i=1}^{5}
\frac{c_i \cos\left\{\pi \left[\left(x_{1}- a_i\right)^{2}
+ \left(x_{2} - b_i \right)^{2}\right]\right\}}{e^{\frac{\left( x_{1}
- a_i\right)^{2} + \left( x_{2} - b_i\right)^{2}}{\pi}}}
Where:
.. math::
\begin{matrix}
a = [3, 5, 2, 1, 7]\\
b = [5, 2, 1, 4, 9]\\
c = [1, 2, 5, 2, 3] \\
\end{matrix}
Here :math:`x_i \in [0, 10]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = -5.1621259`
for :math:`x = [2.00299219, 1.006096]`
.. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015
TODO: Langermann from Gavana is _not the same_ as Jamil #68.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.0] * self.N, [10.0] * self.N))
self.global_optimum = [[2.00299219, 1.006096]]
self.fglob = -5.1621259
def fun(self, x, *args):
self.nfev += 1
a = [3, 5, 2, 1, 7]
b = [5, 2, 1, 4, 9]
c = [1, 2, 5, 2, 3]
return (-sum(c * exp(-(1 / pi) * ((x[0] - a) ** 2 +
(x[1] - b) ** 2)) * cos(pi * ((x[0] - a) ** 2
+ (x[1] - b) ** 2))))
| Langermann |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 7633,
"end": 10635
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def forward(
self,
hidden_states,
attention_mask=None,
output_attentions=False,
):
batch_size, seq_length, _ = hidden_states.shape
query_layer = (
self.query(hidden_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
key_layer = (
self.key(hidden_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
value_layer = (
self.value(hidden_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in VisualBertSelfAttentionModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
return outputs
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->VisualBert
| VisualBertSelfAttention |
python | huggingface__transformers | src/transformers/models/lilt/configuration_lilt.py | {
"start": 775,
"end": 5972
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LiltModel`]. It is used to instantiate a LiLT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the LiLT
[SCUT-DLVCLab/lilt-roberta-en-base](https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the LiLT model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`LiltModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer. Should be a multiple of 24.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
max_position_embeddings (`int`, *optional*, defaults to 512):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
type_vocab_size (`int`, *optional*, defaults to 2):
The vocabulary size of the `token_type_ids` passed when calling [`LiltModel`].
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
classifier_dropout (`float`, *optional*):
The dropout ratio for the classification head.
channel_shrink_ratio (`int`, *optional*, defaults to 4):
The shrink ratio compared to the `hidden_size` for the channel dimension of the layout embeddings.
max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
The maximum value that the 2D position embedding might ever be used with. Typically set this to something
large just in case (e.g., 1024).
Examples:
```python
>>> from transformers import LiltConfig, LiltModel
>>> # Initializing a LiLT SCUT-DLVCLab/lilt-roberta-en-base style configuration
>>> configuration = LiltConfig()
>>> # Randomly initializing a model from the SCUT-DLVCLab/lilt-roberta-en-base style configuration
>>> model = LiltModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "lilt"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=2,
initializer_range=0.02,
layer_norm_eps=1e-12,
pad_token_id=0,
classifier_dropout=None,
channel_shrink_ratio=4,
max_2d_position_embeddings=1024,
**kwargs,
):
super().__init__(pad_token_id=pad_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.classifier_dropout = classifier_dropout
self.channel_shrink_ratio = channel_shrink_ratio
self.max_2d_position_embeddings = max_2d_position_embeddings
__all__ = ["LiltConfig"]
| LiltConfig |
python | google__jax | tests/sparsify_test.py | {
"start": 1602,
"end": 23283
} | class ____(jtu.JaxTestCase):
@classmethod
def sparsify(cls, f):
return sparsify(f, use_tracer=False)
def testNotImplementedMessages(self):
x = BCOO.fromdense(jnp.arange(5.0))
# Test a densifying primitive
with self.assertRaisesRegex(NotImplementedError,
r"^sparse rule for cos is not implemented because it would result in dense output\."):
self.sparsify(lax.cos)(x)
# Test a generic not implemented primitive.
with self.assertRaisesRegex(NotImplementedError,
r"^sparse rule for complex is not implemented\.$"):
self.sparsify(lax.complex)(x, x)
def testTracerIsInstanceCheck(self):
@self.sparsify
def f(x):
self.assertNotIsInstance(x, SparseTracer)
f(jnp.arange(5))
def assertBcooIdentical(self, x, y):
self.assertIsInstance(x, BCOO)
self.assertIsInstance(y, BCOO)
self.assertEqual(x.shape, y.shape)
self.assertArraysEqual(x.data, y.data)
self.assertArraysEqual(x.indices, y.indices)
def testSparsifyValue(self):
X = jnp.arange(5)
X_BCOO = BCOO.fromdense(X)
args = (X, X_BCOO, X_BCOO)
# Independent index
spenv = SparsifyEnv()
spvalues = arrays_to_spvalues(spenv, args)
self.assertEqual(len(spvalues), len(args))
self.assertLen(spenv._buffers, 5)
self.assertEqual(spvalues,
(SparsifyValue(X.shape, 0, None, indices_sorted=False,
unique_indices=False),
SparsifyValue(X.shape, 1, 2, indices_sorted=True,
unique_indices=True),
SparsifyValue(X.shape, 3, 4, indices_sorted=True,
unique_indices=True)))
args_out = spvalues_to_arrays(spenv, spvalues)
self.assertEqual(len(args_out), len(args))
self.assertArraysEqual(args[0], args_out[0])
self.assertBcooIdentical(args[1], args_out[1])
self.assertBcooIdentical(args[2], args_out[2])
# Shared index
spvalues = (SparsifyValue(X.shape, 0, None), SparsifyValue(X.shape, 1, 2), SparsifyValue(X.shape, 3, 2))
spenv = SparsifyEnv([X, X_BCOO.data, X_BCOO.indices, X_BCOO.data])
args_out = spvalues_to_arrays(spenv, spvalues)
self.assertEqual(len(args_out), len(args))
self.assertArraysEqual(args[0], args_out[0])
self.assertBcooIdentical(args[1], args_out[1])
self.assertBcooIdentical(args[2], args_out[2])
def testDropvar(self):
def inner(x):
return x * 2, x * 3
def f(x):
_, y = jit(inner)(x)
return y * 4
x_dense = jnp.arange(5)
x_sparse = BCOO.fromdense(x_dense)
self.assertArraysEqual(self.sparsify(f)(x_sparse).todense(), f(x_dense))
def testPytreeInput(self):
f = self.sparsify(lambda x: x)
args = (jnp.arange(4), BCOO.fromdense(jnp.arange(4)))
out = f(args)
self.assertLen(out, 2)
self.assertArraysEqual(args[0], out[0])
self.assertBcooIdentical(args[1], out[1])
@jax.numpy_dtype_promotion('standard') # explicitly exercises implicit dtype promotion.
def testSparsify(self):
M_dense = jnp.arange(24).reshape(4, 6)
M_sparse = BCOO.fromdense(M_dense)
v = jnp.arange(M_dense.shape[0])
@self.sparsify
def func(x, v):
return -jnp.sin(jnp.pi * x).T @ (v + 1)
with jtu.ignore_warning(
category=CuSparseEfficiencyWarning,
message="bcoo_dot_general GPU lowering requires matrices with sorted indices*"):
result_sparse = func(M_sparse, v)
result_dense = func(M_dense, v)
self.assertAllClose(result_sparse, result_dense)
def testSparsifyWithConsts(self):
M_dense = jnp.arange(24).reshape(4, 6)
M_sparse = BCOO.fromdense(M_dense)
@self.sparsify
def func(x):
return jit(lambda x: jnp.sum(x, 1))(x)
result_dense = func(M_dense)
result_sparse = func(M_sparse)
self.assertAllClose(result_sparse.todense(), result_dense)
@jax.numpy_dtype_promotion('standard')
def testSparseMatmul(self):
X = jnp.arange(16.0, dtype='float32').reshape(4, 4)
Xsp = BCOO.fromdense(X)
Y = jnp.ones(4, dtype='int32')
Ysp = BCOO.fromdense(Y)
# Note: deliberately testing with mixed precision
assert Xsp.dtype != Ysp.dtype
# dot_general
result_sparse = self.sparsify(lax.dot)(Xsp, Y)
result_dense = lax.dot(X, Y)
self.assertAllClose(result_sparse, result_dense)
# rdot_general
result_sparse = self.sparsify(lax.dot)(Y, Xsp)
result_dense = lax.dot(Y, X)
self.assertAllClose(result_sparse, result_dense)
# spdot_general
result_sparse = self.sparsify(lax.dot)(Xsp, Ysp)
result_dense = lax.dot(X, Y)
self.assertAllClose(result_sparse.todense(), result_dense)
def testSparseAdd(self):
x = BCOO.fromdense(jnp.arange(5))
y = BCOO.fromdense(2 * jnp.arange(5))
# Distinct indices
out = self.sparsify(operator.add)(x, y)
self.assertEqual(out.nse, 8) # uses concatenation.
self.assertArraysEqual(out.todense(), 3 * jnp.arange(5))
# Shared indices – requires lower level call
spenv = SparsifyEnv([x.indices, x.data, y.data])
spvalues = [
spenv.sparse(x.shape, data_ref=1, indices_ref=0),
spenv.sparse(y.shape, data_ref=2, indices_ref=0)
]
result = sparsify_raw(operator.add)(spenv, *spvalues)
args_out, _ = result
out, = spvalues_to_arrays(spenv, args_out)
self.assertAllClose(out.todense(), x.todense() + y.todense())
# Sparse + dense: supported
x = BCOO.fromdense(jnp.arange(6.)).reshape(2, 3)
y = jnp.ones((2, 3))
out = self.sparsify(operator.add)(x, y)
self.assertAllClose(out, x.todense() + y)
out = self.sparsify(operator.add)(y, x)
self.assertAllClose(out, x.todense() + y)
# Sparse + dense: unsupported
msg = "Addition between a sparse array X and a dense array Y is not implemented"
with self.assertRaisesRegex(NotImplementedError, msg):
self.sparsify(operator.add)(x, 1.)
@jtu.sample_product(
[dict(shape=shape, n_batch=n_batch, n_dense=n_dense)
for shape in [(5,), (5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]
for n_batch in range(len(shape) + 1)
for n_dense in range(len(shape) + 1 - n_batch)
],
dtype=jtu.dtypes.integer + jtu.dtypes.floating + jtu.dtypes.complex,
unique_indices=[True, False],
)
def testSparseMul(self, shape, dtype, n_batch, n_dense, unique_indices):
rng_sparse = rand_sparse(self.rng(), rand_method=jtu.rand_some_zero)
x = BCOO.fromdense(rng_sparse(shape, dtype), n_batch=n_batch,
n_dense=n_dense)
# Scalar multiplication
scalar = 2
y = self.sparsify(operator.mul)(x, scalar)
self.assertArraysEqual(x.todense() * scalar, y.todense())
# Shared indices – requires lower level call
spenv = SparsifyEnv([x.indices, x.data, y.data])
spvalues = [
spenv.sparse(x.shape, data_ref=1, indices_ref=0,
unique_indices=unique_indices),
spenv.sparse(y.shape, data_ref=2, indices_ref=0,
unique_indices=unique_indices)
]
result = sparsify_raw(operator.mul)(spenv, *spvalues)
args_out, _ = result
out, = spvalues_to_arrays(spenv, args_out)
self.assertAllClose(out.todense(), x.todense() * y.todense())
@jtu.sample_product(
[dict(shape=shape, n_batch=n_batch, n_dense=n_dense)
for shape in [(5,), (5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]
for n_batch in range(len(shape) + 1)
for n_dense in range(len(shape) + 1 - n_batch)
],
dtype=jtu.dtypes.integer + jtu.dtypes.floating + jtu.dtypes.complex,
)
def testSparseDiv(self, shape, dtype, n_batch, n_dense):
rng_dense = jtu.rand_nonzero(self.rng())
rng_sparse = rand_sparse(self.rng(), rand_method=jtu.rand_some_zero)
x = BCOO.fromdense(rng_sparse(shape, dtype), n_batch=n_batch,
n_dense=n_dense)
spdiv = self.sparsify(operator.truediv)
# Scalar division
divisor = 2
expected = x.todense() / divisor
self.assertAllClose(expected, spdiv(x, divisor).todense())
self.assertAllClose(expected, (x / divisor).todense())
# Array division
divisor = rng_dense(shape, dtype)
expected = x.todense() / divisor
self.assertAllClose(expected, spdiv(x, divisor).todense())
self.assertAllClose(expected, (x / divisor).todense())
def testSparseSubtract(self):
x = BCOO.fromdense(3 * jnp.arange(5))
y = BCOO.fromdense(jnp.arange(5))
# Distinct indices
out = self.sparsify(operator.sub)(x, y)
self.assertEqual(out.nse, 8) # uses concatenation.
self.assertArraysEqual(out.todense(), 2 * jnp.arange(5))
# Shared indices – requires lower level call
spenv = SparsifyEnv([x.indices, x.data, y.data])
spvalues = [
spenv.sparse(x.shape, data_ref=1, indices_ref=0),
spenv.sparse(y.shape, data_ref=2, indices_ref=0)
]
result = sparsify_raw(operator.sub)(spenv, *spvalues)
args_out, _ = result
out, = spvalues_to_arrays(spenv, args_out)
self.assertAllClose(out.todense(), x.todense() - y.todense())
def testSparsePow(self):
x = jnp.arange(20.0).reshape(4, 5)
xsp = BCOO.fromdense(x)
result_dense = x ** 2
result_sparse = xsp ** 2
self.assertAllClose(result_dense, result_sparse.todense())
with self.assertRaisesRegex(NotImplementedError,
"sparse rule for integer_pow with non-positive exponent"):
_ = xsp ** -1
def testSparseSum(self):
x = jnp.arange(20).reshape(4, 5)
xsp = BCOO.fromdense(x)
def f(x):
return x.sum(), x.sum(0), x.sum(1), x.sum((0, 1))
result_dense = f(x)
result_sparse = self.sparsify(f)(xsp)
assert len(result_dense) == len(result_sparse)
for res_dense, res_sparse in zip(result_dense, result_sparse):
if isinstance(res_sparse, BCOO):
res_sparse = res_sparse.todense()
self.assertArraysAllClose(res_dense, res_sparse)
def testSparseSqueeze(self):
# Note: more comprehensive tests in sparse_test.py:test_bcoo_squeeze
rng = jtu.rand_default(self.rng())
M_dense = rng((2, 3, 1, 4), np.float32)
M_sparse = BCOO.fromdense(M_dense)
func = self.sparsify(partial(lax.squeeze, dimensions=(2,)))
result_dense = func(M_dense)
result_sparse = func(M_sparse).todense()
self.assertAllClose(result_sparse, result_dense)
def testSparseRev(self):
# Note: more comprehensive tests in sparse_test.py:test_bcoo_rev
rng = jtu.rand_default(self.rng())
M_dense = rng((2, 3, 4), np.float32)
M_sparse = BCOO.fromdense(M_dense)
func = self.sparsify(partial(lax.rev, dimensions=(1, 2)))
result_dense = func(M_dense)
result_sparse = func(M_sparse).todense()
self.assertAllClose(result_sparse, result_dense)
@jtu.sample_product(
[dict(shapes=shapes, func=func, n_batch=n_batch)
for shapes, func, n_batch in [
([(4,), (4,)], "concatenate", 0),
([(4,), (4,)], "stack", 0),
([(4,), (4,)], "hstack", 0),
([(4,), (4,)], "vstack", 0),
([(4,), (4,)], "concatenate", 1),
([(4,), (4,)], "stack", 1),
([(4,), (4,)], "hstack", 1),
([(4,), (4,)], "vstack", 1),
([(2, 4), (2, 4)], "stack", 0),
([(2, 4), (3, 4)], "vstack", 0),
([(2, 4), (2, 5)], "hstack", 0),
([(2, 4), (3, 4)], "vstack", 1),
([(2, 4), (2, 5)], "hstack", 1),
([(2, 4), (3, 4)], "vstack", 2),
([(2, 4), (2, 5)], "hstack", 2),
([(2, 4), (4,), (3, 4)], "vstack", 0),
([(1, 4), (4,), (1, 4)], "vstack", 0),
]
]
)
def testSparseConcatenateBCOO(self, shapes, func, n_batch):
f = self.sparsify(getattr(jnp, func))
rng = jtu.rand_some_zero(self.rng())
arrs = [rng(shape, 'int32') for shape in shapes]
sparrs = [BCOO.fromdense(arr, n_batch=n_batch) for arr in arrs]
self.assertArraysEqual(f(arrs), f(sparrs).todense())
@jtu.sample_product(
[dict(shapes=shapes, func=func, n_batch=n_batch)
for shapes, func, n_batch in [
([(2, 4), (2, 4)], "stack", 0),
([(2, 4), (3, 4)], "vstack", 0),
([(2, 4), (2, 5)], "hstack", 0),
([(2, 4), (3, 4)], "vstack", 1),
([(2, 4), (2, 5)], "hstack", 1),
([(2, 4), (3, 4)], "vstack", 2),
([(2, 4), (2, 5)], "hstack", 2),
]
]
)
def testSparseConcatenateBCSR(self, shapes, func, n_batch):
f = self.sparsify(getattr(jnp, func))
rng = jtu.rand_some_zero(self.rng())
arrs = [rng(shape, 'int32') for shape in shapes]
sparrs = [BCOO.fromdense(arr, n_batch=n_batch) for arr in arrs]
self.assertArraysEqual(f(arrs), f(sparrs).todense())
@jax.default_matmul_precision("float32")
def testSparseConvolve(self, lhs_shape=(10,), rhs_shape=(5,),
dtype='float32', mode='full'):
# Note: more comprehensive tests in sparse_test.py:test_bcoo_conv_general_dilated
dense_fun = partial(jnp.convolve, mode=mode)
sparse_fun = self.sparsify(dense_fun)
sprng = sptu.rand_bcoo(self.rng())
rng = jtu.rand_default(self.rng())
lhs = sprng(lhs_shape, dtype)
rhs = rng(rhs_shape, dtype)
expected = dense_fun(lhs.todense(), rhs)
actual = sparse_fun(lhs, rhs).todense()
tol = {np.float32: 1E-5, np.complex64: 1E-5, np.float64: 1E-14, np.complex128: 1E-14}
self.assertAllClose(expected, actual, atol=tol, rtol=tol)
def testSparseReshapeMethod(self):
# Note: this is more fully tested in sparse_test.py:test_bcoo_reshape
shape = (2, 3, 4)
new_shape = (2, 6, 2)
rng = jtu.rand_some_zero(self.rng())
arr = rng(shape, 'int32')
arr_sparse = BCOO.fromdense(arr, n_batch=1)
arr2 = arr.reshape(new_shape)
arr2_sparse = arr_sparse.reshape(new_shape)
arr2_sparse_jit = jax.jit(lambda x: x.reshape(new_shape))(arr_sparse)
self.assertArraysEqual(arr2, arr2_sparse.todense())
self.assertArraysEqual(arr2, arr2_sparse_jit.todense())
def testSparseWhileLoop(self):
def cond_fun(params):
i, A = params
return i < 5
def body_fun(params):
i, A = params
return i + 1, 2 * A
def f(A):
return lax.while_loop(cond_fun, body_fun, (0, A))
A = jnp.arange(4)
out_dense = f(A)
Asp = BCOO.fromdense(A)
out_sparse = self.sparsify(f)(Asp)
self.assertEqual(len(out_dense), 2)
self.assertEqual(len(out_sparse), 2)
self.assertArraysEqual(out_dense[0], out_dense[0])
self.assertArraysEqual(out_dense[1], out_sparse[1].todense())
def testSparseWhileLoopDuplicateIndices(self):
def cond_fun(params):
i, A, B = params
return i < 5
def body_fun(params):
i, A, B = params
# TODO(jakevdp): track shared indices through while loop & use this
# version of the test, which requires shared indices in order for
# the nse of the result to remain the same.
# return i + 1, A, A + B
# This version is fine without shared indices, and tests that we're
# flattening non-shared indices consistently.
return i + 1, B, A
def f(A):
return lax.while_loop(cond_fun, body_fun, (0, A, A))
A = jnp.arange(4).reshape((2, 2))
out_dense = f(A)
Asp = BCOO.fromdense(A)
out_sparse = self.sparsify(f)(Asp)
self.assertEqual(len(out_dense), 3)
self.assertEqual(len(out_sparse), 3)
self.assertArraysEqual(out_dense[0], out_dense[0])
self.assertArraysEqual(out_dense[1], out_sparse[1].todense())
self.assertArraysEqual(out_dense[2], out_sparse[2].todense())
def testSparsifyDenseXlaCall(self):
# Test handling of dense xla_call within jaxpr interpreter.
out = self.sparsify(jit(lambda x: x + 1))(0.0)
self.assertEqual(out, 1.0)
def testSparsifySparseXlaCall(self):
# Test sparse lowering of XLA call
def func(M):
return 2 * M
M = jnp.arange(6).reshape(2, 3)
Msp = BCOO.fromdense(M)
out_dense = func(M)
out_sparse = self.sparsify(jit(func))(Msp)
self.assertArraysEqual(out_dense, out_sparse.todense())
def testSparseForiLoop(self):
def func(M, x):
body_fun = lambda i, val: (M @ val) / M.shape[1]
return lax.fori_loop(0, 2, body_fun, x)
x = jnp.arange(5.0)
M = jnp.arange(25).reshape(5, 5)
M_bcoo = BCOO.fromdense(M)
with jax.numpy_dtype_promotion('standard'):
result_dense = func(M, x)
result_sparse = self.sparsify(func)(M_bcoo, x)
self.assertArraysAllClose(result_dense, result_sparse)
def testSparseCondSimple(self):
def func(x):
return lax.cond(False, lambda x: x, lambda x: 2 * x, x)
x = jnp.arange(5.0)
result_dense = func(x)
x_bcoo = BCOO.fromdense(x)
result_sparse = self.sparsify(func)(x_bcoo)
self.assertArraysAllClose(result_dense, result_sparse.todense())
def testSparseCondMismatchError(self):
@self.sparsify
def func(x, y):
return lax.cond(False, lambda x: x[0], lambda x: x[1], (x, y))
x = jnp.arange(5.0)
y = jnp.arange(5.0)
x_bcoo = BCOO.fromdense(x)
y_bcoo = BCOO.fromdense(y)
func(x, y) # No error
func(x_bcoo, y_bcoo) # No error
with self.assertRaisesRegex(
TypeError,
"sparsified true_fun output must have same type structure as sparsified false_fun output.*"):
func(x_bcoo, y)
@parameterized.named_parameters(
{"testcase_name": f"_{fmt}", "fmt": fmt}
for fmt in ["BCSR", "BCOO"]
)
def testToDense(self, fmt):
M = jnp.arange(4).reshape(2, 2)
if fmt == "BCOO":
Msp = BCOO.fromdense(M)
elif fmt == "BCSR":
Msp = BCSR.fromdense(M)
else:
raise ValueError(f"Unrecognized {fmt=}")
@self.sparsify
def func(M):
return todense(M) + 1
self.assertArraysEqual(func(M), M + 1)
self.assertArraysEqual(func(Msp), M + 1)
self.assertArraysEqual(jit(func)(M), M + 1)
self.assertArraysEqual(jit(func)(Msp), M + 1)
def testSparseSlice(self):
M = jnp.arange(24).reshape(2, 3, 4)
Msp = BCOO.fromdense(M)
@self.sparsify
def func(M):
return lax.slice(M, (0, 1, 2), (1, 3, 3))
expected = M[:1, 1:3, 2:3]
self.assertArraysEqual(func(M), expected)
self.assertArraysEqual(func(Msp).todense(), expected)
self.assertArraysEqual(jit(func)(M), expected)
self.assertArraysEqual(jit(func)(Msp).todense(), expected)
def testSparseDynamicSlice(self):
M = jnp.arange(24).reshape(2, 3, 4)
Msp = BCOO.fromdense(M)
@self.sparsify
def func(M):
return lax.dynamic_slice(M, (0, 1, 2), (1, 1, 3))
expected = M[:1, 1:2, 1:4]
self.assertArraysEqual(func(M), expected)
self.assertArraysEqual(func(Msp).todense(), expected)
self.assertArraysEqual(jit(func)(M), expected)
self.assertArraysEqual(jit(func)(Msp).todense(), expected)
def testWeakTypes(self):
# Regression test for https://github.com/jax-ml/jax/issues/8267
M = jnp.arange(12, dtype='int32').reshape(3, 4)
Msp = BCOO.fromdense(M)
self.assertArraysEqual(
operator.mul(2, M),
self.sparsify(operator.mul)(2, Msp).todense(),
check_dtypes=True,
)
@parameterized.named_parameters(
{"testcase_name": f"_{op.__name__}_{fmt}", "op": op, "dtype": dtype,
"kwds": kwds, "fmt": fmt}
for fmt in ["BCSR", "BCOO"]
for op, dtype, kwds in [
(jnp.copy, jnp.float32, {}),
(lax.conj, jnp.complex64, {}),
(lax.abs, jnp.float32, {}),
(lax.asin, jnp.float32, {}),
(lax.asinh, jnp.float32, {}),
(lax.atan, jnp.float32, {}),
(lax.atanh, jnp.float32, {}),
(lax.bessel_i1e, jnp.float32, {}),
(lax.expm1, jnp.float32, {}),
(lax.log1p, jnp.float32, {}),
(lax.neg, jnp.float32, {}),
(lax.real, jnp.complex64, {}),
(lax.imag, jnp.complex64, {}),
(lax.sign, jnp.float32, {}),
(lax.sin, jnp.float32, {}),
(lax.sinh, jnp.float32, {}),
(lax.sqrt, jnp.float32, {}),
(lax.tan, jnp.float32, {}),
(lax.tanh, jnp.float32, {}),
(lax.convert_element_type, jnp.float32, {"new_dtype": np.dtype('complex64')}),
(lax.integer_pow, jnp.float32, {'y': 2})])
def testUnaryOperationsNonUniqueIndices(self, fmt, op, dtype, kwds):
shape = (4, 5)
# Note: we deliberately test non-unique indices here.
if fmt == "BCOO":
rng = sptu.rand_bcoo(self.rng())
elif fmt == "BCSR":
rng = sptu.rand_bcsr(self.rng())
else:
raise ValueError(f"Unrecognized {fmt=}")
mat = rng(shape, dtype)
sparse_result = self.sparsify(partial(op, **kwds))(mat)
dense_result = op(mat.todense(), **kwds)
self.assertArraysAllClose(sparse_result.todense(), dense_result)
# Ops that commute with addition should not deduplicate indices.
if op in [jnp.copy, lax.neg, lax.real, lax.imag]:
self.assertArraysAllClose(sparse_result.indices, mat.indices)
if fmt == "BCSR":
self.assertArraysAllClose(sparse_result.indptr, mat.indptr)
def testCustomJVP(self):
square = jax.custom_derivatives.custom_jvp(lambda x: x ** 2)
square.defjvp(lambda p, t: (p[0] ** 2, 2 * t[0] * p[0]))
x = BCOO.fromdense(jnp.arange(5.0))
# Test calling the function itself.
result = self.sparsify(square)(x)
expected = self.sparsify(lambda x: x ** 2)(x)
self.assertArraysEqual(result.indices, expected.indices)
self.assertArraysAllClose(result.data, expected.data)
# Test evaluating the custom gradient.
grad_square_sum = jax.grad(lambda x: square(x).sum())
result = self.sparsify(grad_square_sum)(x)
expected = self.sparsify(jax.grad(lambda x: jnp.sum(x ** 2)))(x)
self.assertArraysEqual(result.indices, expected.indices)
self.assertArraysAllClose(result.data, expected.data)
| SparsifyTest |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py | {
"start": 8507,
"end": 8948
} | class ____(BaseModel):
@abstractmethod
def search_settings(self, exclude_none: bool = True) -> dict[str, Any]:
"""Return the specific index search settings for the algorithm.
:param exclude_none: Whether to exclude keys with None values in the dictionary.
:type exclude_none: bool
:return: A dictionary containing the search settings.
:rtype: dict[str, Any]
"""
...
| SearchParams |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/metadata_replacement.py | {
"start": 236,
"end": 1067
} | class ____(BaseNodePostprocessor):
target_metadata_key: str = Field(
description="Target metadata key to replace node content with."
)
def __init__(self, target_metadata_key: str) -> None:
super().__init__(target_metadata_key=target_metadata_key)
@classmethod
def class_name(cls) -> str:
return "MetadataReplacementPostProcessor"
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
for n in nodes:
n.node.set_content(
n.node.metadata.get(
self.target_metadata_key,
n.node.get_content(metadata_mode=MetadataMode.NONE),
)
)
return nodes
| MetadataReplacementPostProcessor |
python | django__django | tests/model_fields/models.py | {
"start": 4726,
"end": 4953
} | class ____(models.Model):
"""Model with FKs to models with {Null,}BooleanField's, #15040"""
bf = models.ForeignKey(BooleanModel, models.CASCADE)
nbf = models.ForeignKey(NullBooleanModel, models.CASCADE)
| FksToBooleans |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 187929,
"end": 193671
} | class ____(AssertsCompiledSQL, fixtures.TestBase):
__dialect__ = "postgresql"
# operator tests
@classmethod
def setup_test_class(cls):
table = Table(
"data_table",
MetaData(),
Column("multirange", cls._col_type, primary_key=True),
)
cls.col = table.c.multirange
def _test_clause(self, colclause, expected, type_):
self.assert_compile(colclause, expected)
is_(colclause.type._type_affinity, type_._type_affinity)
def test_where_equal(self):
self._test_clause(
self.col == self._data_str(),
"data_table.multirange = %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_where_equal_obj(self):
self._test_clause(
self.col == self._data_obj(),
f"data_table.multirange = %(multirange_1)s::{self._col_str}",
sqltypes.BOOLEANTYPE,
)
def test_where_not_equal(self):
self._test_clause(
self.col != self._data_str(),
"data_table.multirange != %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_where_not_equal_obj(self):
self._test_clause(
self.col != self._data_obj(),
f"data_table.multirange != %(multirange_1)s::{self._col_str}",
sqltypes.BOOLEANTYPE,
)
def test_where_is_null(self):
self._test_clause(
self.col == None,
"data_table.multirange IS NULL",
sqltypes.BOOLEANTYPE,
)
def test_where_is_not_null(self):
self._test_clause(
self.col != None,
"data_table.multirange IS NOT NULL",
sqltypes.BOOLEANTYPE,
)
def test_where_less_than(self):
self._test_clause(
self.col < self._data_str(),
"data_table.multirange < %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_where_greater_than(self):
self._test_clause(
self.col > self._data_str(),
"data_table.multirange > %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_where_less_than_or_equal(self):
self._test_clause(
self.col <= self._data_str(),
"data_table.multirange <= %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_where_greater_than_or_equal(self):
self._test_clause(
self.col >= self._data_str(),
"data_table.multirange >= %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_contains(self):
self._test_clause(
self.col.contains(self._data_str()),
"data_table.multirange @> %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_contained_by(self):
self._test_clause(
self.col.contained_by(self._data_str()),
"data_table.multirange <@ %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_contained_by_obj(self):
self._test_clause(
self.col.contained_by(self._data_obj()),
f"data_table.multirange <@ %(multirange_1)s::{self._col_str}",
sqltypes.BOOLEANTYPE,
)
def test_overlaps(self):
self._test_clause(
self.col.overlaps(self._data_str()),
"data_table.multirange && %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_strictly_left_of(self):
self._test_clause(
self.col << self._data_str(),
"data_table.multirange << %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
self._test_clause(
self.col.strictly_left_of(self._data_str()),
"data_table.multirange << %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_strictly_right_of(self):
self._test_clause(
self.col >> self._data_str(),
"data_table.multirange >> %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
self._test_clause(
self.col.strictly_right_of(self._data_str()),
"data_table.multirange >> %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_not_extend_right_of(self):
self._test_clause(
self.col.not_extend_right_of(self._data_str()),
"data_table.multirange &< %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_not_extend_left_of(self):
self._test_clause(
self.col.not_extend_left_of(self._data_str()),
"data_table.multirange &> %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_adjacent_to(self):
self._test_clause(
self.col.adjacent_to(self._data_str()),
"data_table.multirange -|- %(multirange_1)s",
sqltypes.BOOLEANTYPE,
)
def test_adjacent_to_obj(self):
self._test_clause(
self.col.adjacent_to(self._data_obj()),
f"data_table.multirange -|- %(multirange_1)s::{self._col_str}",
sqltypes.BOOLEANTYPE,
)
def test_union(self):
self._test_clause(
self.col + self.col,
"data_table.multirange + data_table.multirange",
self.col.type,
)
def test_intersection(self):
self._test_clause(
self.col * self.col,
"data_table.multirange * data_table.multirange",
self.col.type,
)
def test_difference(self):
self._test_clause(
self.col - self.col,
"data_table.multirange - data_table.multirange",
self.col.type,
)
| _MultiRangeTypeCompilation |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_meid.py | {
"start": 855,
"end": 1842
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.to_be_valid_meid"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_meid(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidMeid |
python | getsentry__sentry | tests/sentry/utils/test_http.py | {
"start": 2816,
"end": 9060
} | class ____(unittest.TestCase):
def isValidOrigin(self, origin, inputs):
with mock.patch("sentry.utils.http.get_origins") as get_origins:
get_origins.return_value = inputs
project = mock.Mock()
result = is_valid_origin(origin, project)
get_origins.assert_called_once_with(project)
return result
def test_global_wildcard_matches_domain(self) -> None:
result = self.isValidOrigin("http://example.com", ["*"])
self.assertEqual(result, True)
def test_domain_wildcard_matches_domain(self) -> None:
result = self.isValidOrigin("http://example.com", ["*.example.com"])
self.assertEqual(result, True)
def test_domain_wildcard_matches_domain_with_port(self) -> None:
result = self.isValidOrigin("http://example.com:80", ["*.example.com"])
self.assertEqual(result, True)
def test_domain_wildcard_matches_subdomain(self) -> None:
result = self.isValidOrigin("http://foo.example.com", ["*.example.com"])
self.assertEqual(result, True)
def test_domain_wildcard_matches_subdomain_with_port(self) -> None:
result = self.isValidOrigin("http://foo.example.com:80", ["*.example.com"])
self.assertEqual(result, True)
def test_domain_wildcard_does_not_match_others(self) -> None:
result = self.isValidOrigin("http://foo.com", ["*.example.com"])
self.assertEqual(result, False)
def test_domain_wildcard_matches_domain_with_path(self) -> None:
result = self.isValidOrigin("http://foo.example.com/foo/bar", ["*.example.com"])
self.assertEqual(result, True)
def test_base_domain_matches_domain(self) -> None:
result = self.isValidOrigin("http://example.com", ["example.com"])
self.assertEqual(result, True)
def test_base_domain_matches_domain_with_path(self) -> None:
result = self.isValidOrigin("http://example.com/foo/bar", ["example.com"])
self.assertEqual(result, True)
def test_base_domain_matches_domain_with_port(self) -> None:
result = self.isValidOrigin("http://example.com:80", ["example.com"])
self.assertEqual(result, True)
def test_base_domain_matches_domain_with_explicit_port(self) -> None:
result = self.isValidOrigin("http://example.com:80", ["example.com:80"])
assert result is True
def test_base_domain_does_not_match_domain_with_invalid_port(self) -> None:
result = self.isValidOrigin("http://example.com:80", ["example.com:443"])
assert result is False
def test_base_domain_does_not_match_subdomain(self) -> None:
result = self.isValidOrigin("http://example.com", ["foo.example.com"])
self.assertEqual(result, False)
def test_full_uri_match(self) -> None:
result = self.isValidOrigin("http://example.com", ["http://example.com"])
self.assertEqual(result, True)
def test_full_uri_match_requires_scheme(self) -> None:
result = self.isValidOrigin("https://example.com", ["http://example.com"])
self.assertEqual(result, False)
def test_full_uri_match_does_not_require_port(self) -> None:
result = self.isValidOrigin("http://example.com:80", ["http://example.com"])
self.assertEqual(result, True)
def test_partial_uri_match(self) -> None:
result = self.isValidOrigin("http://example.com/foo/bar", ["http://example.com"])
self.assertEqual(result, True)
def test_null_valid_with_global(self) -> None:
result = self.isValidOrigin("null", ["*"])
self.assertEqual(result, True)
def test_null_invalid_graceful_with_domains(self) -> None:
result = self.isValidOrigin("null", ["http://example.com"])
self.assertEqual(result, False)
def test_custom_protocol_with_location(self) -> None:
result = self.isValidOrigin("sp://custom-thing/foo/bar", ["sp://custom-thing"])
assert result is True
result = self.isValidOrigin("sp://custom-thing-two/foo/bar", ["sp://custom-thing"])
assert result is False
def test_custom_protocol_without_location(self) -> None:
result = self.isValidOrigin("sp://custom-thing/foo/bar", ["sp://*"])
assert result is True
result = self.isValidOrigin("dp://custom-thing/foo/bar", ["sp://"])
assert result is False
def test_custom_protocol_with_domainish_match(self) -> None:
result = self.isValidOrigin("sp://custom-thing.foobar/foo/bar", ["sp://*.foobar"])
assert result is True
result = self.isValidOrigin("sp://custom-thing.bizbaz/foo/bar", ["sp://*.foobar"])
assert result is False
def test_unicode(self) -> None:
result = self.isValidOrigin("http://l\xf8calhost", ["*.l\xf8calhost"])
assert result is True
def test_punycode(self) -> None:
result = self.isValidOrigin("http://xn--lcalhost-54a", ["*.l\xf8calhost"])
assert result is True
result = self.isValidOrigin("http://xn--lcalhost-54a", ["*.xn--lcalhost-54a"])
assert result is True
result = self.isValidOrigin("http://l\xf8calhost", ["*.xn--lcalhost-54a"])
assert result is True
result = self.isValidOrigin("http://xn--lcalhost-54a", ["l\xf8calhost"])
assert result is True
result = self.isValidOrigin("http://xn--lcalhost-54a:80", ["l\xf8calhost:80"])
assert result is True
def test_unparseable_uri(self) -> None:
result = self.isValidOrigin("http://example.com", ["."])
assert result is False
def test_wildcard_hostname_with_port(self) -> None:
result = self.isValidOrigin("http://example.com:1234", ["*:1234"])
assert result is True
def test_without_hostname(self) -> None:
result = self.isValidOrigin("foo://", ["foo://*"])
assert result is True
result = self.isValidOrigin("foo://", ["foo://"])
assert result is True
result = self.isValidOrigin("foo://", ["example.com"])
assert result is False
result = self.isValidOrigin("foo://a", ["foo://"])
assert result is False
result = self.isValidOrigin("foo://a", ["foo://*"])
assert result is True
| IsValidOriginTestCase |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 10511,
"end": 10592
} | class ____(BitwiseLogicOperation):
pass
@infer_global(operator.iand)
| BitwiseAnd |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_scheduler.py | {
"start": 41701,
"end": 44368
} | class ____:
"""Tests scheduler service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"scheduler": {
"serviceAccount": {"create": True},
"labels": {"test_label": "test_label_value"},
},
},
show_only=["templates/scheduler/scheduler-serviceaccount.yaml"],
)
assert "test_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_label"] == "test_label_value"
@pytest.mark.parametrize(
("executor", "default_automount_service_account"),
[
("LocalExecutor", None),
("CeleryExecutor", True),
("CeleryKubernetesExecutor", None),
("KubernetesExecutor", None),
("LocalKubernetesExecutor", None),
("CeleryExecutor,KubernetesExecutor", None),
],
)
def test_default_automount_service_account_token(self, executor, default_automount_service_account):
docs = render_chart(
values={
"scheduler": {
"serviceAccount": {"create": True},
},
"executor": executor,
},
show_only=["templates/scheduler/scheduler-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is default_automount_service_account
@pytest.mark.parametrize(
("executor", "automount_service_account", "should_automount_service_account"),
[
("LocalExecutor", True, None),
("CeleryExecutor", False, False),
("CeleryKubernetesExecutor", False, None),
("KubernetesExecutor", False, None),
("LocalKubernetesExecutor", False, None),
("CeleryExecutor,KubernetesExecutor", False, None),
],
)
def test_overridden_automount_service_account_token(
self, executor, automount_service_account, should_automount_service_account
):
docs = render_chart(
values={
"scheduler": {
"serviceAccount": {
"create": True,
"automountServiceAccountToken": automount_service_account,
},
},
"executor": executor,
},
show_only=["templates/scheduler/scheduler-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is should_automount_service_account
| TestSchedulerServiceAccount |
python | pytorch__pytorch | torch/_inductor/codegen/simd.py | {
"start": 9696,
"end": 12211
} | class ____(IterationRanges):
def __init__(
self,
name: str,
divisor: sympy.Expr,
length: sympy.Expr,
expr: sympy.Expr,
parent: IterationRanges,
) -> None:
super().__init__(
name=name,
numel=parent.numel / length,
var_list=parent.var_list,
var_ranges=parent.var_ranges,
prefix=parent.prefix,
divisor=divisor,
length=length,
kernel=parent.kernel,
root=parent.root,
)
self.parent = parent
self.codegen = functools.lru_cache(None)(self._codegen)
self.expr = expr
def __repr__(self) -> str:
return f"IterationRangesEntry({self.name}, {self.divisor}, {self.length}, {self.expr}, {self.var_ranges})"
def set_name(self, name: str) -> None:
self.codegen = lambda: name # type: ignore[assignment]
self.codegen.cache_clear = lambda: None # type: ignore[method-assign]
self.name = name
def cache_clear(self) -> None:
self.codegen.cache_clear()
def _codegen(self) -> str:
V.kernel.codegen_iteration_ranges_entry(self)
return self.name
def precomputed_args(self) -> list[sympy.Expr]:
# for dynamic shapes, find parts of indexing expressions that have to be precomputed
precomputed_args: list[sympy.Expr] = []
if isinstance(self.expr, sympy.Symbol):
return precomputed_args
assert isinstance(self.expr, (FloorDiv, ModularIndexing)), type(self.expr)
for arg in self.expr.args[1:]:
if not isinstance(arg, (sympy.Integer, sympy.Symbol)):
symbols = arg.free_symbols
if len(symbols) > 0 and all(
symbol_is_type(s, SymT.SIZE) for s in symbols
):
precomputed_args.append(arg)
return precomputed_args
def __hash__(self) -> int:
return hash(self.name)
def __eq__(self, other: object) -> bool:
assert isinstance(other, IterationRangesEntry)
return self.name == other.name
def constant_repr(value: Union[int, float]) -> str:
if value == float("inf"):
return 'float("inf")'
elif value == float("-inf"):
return 'float("-inf")'
elif math.isnan(value):
return 'float("nan")'
return repr(value)
CSEVariableType = TypeVar("CSEVariableType", bound=CSEVariable, default=CSEVariable)
@dataclasses.dataclass
| IterationRangesEntry |
python | pandas-dev__pandas | asv_bench/benchmarks/strings.py | {
"start": 1638,
"end": 4217
} | class ____(Dtypes):
def time_center(self, dtype):
self.s.str.center(100)
def time_count(self, dtype):
self.s.str.count("A")
def time_endswith(self, dtype):
self.s.str.endswith("A")
def time_extract(self, dtype):
with warnings.catch_warnings(record=True):
self.s.str.extract("(\\w*)A(\\w*)")
def time_findall(self, dtype):
self.s.str.findall("[A-Z]+")
def time_find(self, dtype):
self.s.str.find("[A-Z]+")
def time_rfind(self, dtype):
self.s.str.rfind("[A-Z]+")
def time_fullmatch(self, dtype):
self.s.str.fullmatch("A")
def time_get(self, dtype):
self.s.str.get(0)
def time_len(self, dtype):
self.s.str.len()
def time_join(self, dtype):
self.s.str.join(" ")
def time_match(self, dtype):
self.s.str.match("A")
def time_normalize(self, dtype):
self.s.str.normalize("NFC")
def time_pad(self, dtype):
self.s.str.pad(100, side="both")
def time_partition(self, dtype):
self.s.str.partition("A")
def time_rpartition(self, dtype):
self.s.str.rpartition("A")
def time_replace(self, dtype):
self.s.str.replace("A", "\x01\x01")
def time_translate(self, dtype):
self.s.str.translate({"A": "\x01\x01"})
def time_slice(self, dtype):
self.s.str.slice(5, 15, 2)
def time_startswith(self, dtype):
self.s.str.startswith("A")
def time_strip(self, dtype):
self.s.str.strip("A")
def time_rstrip(self, dtype):
self.s.str.rstrip("A")
def time_lstrip(self, dtype):
self.s.str.lstrip("A")
def time_title(self, dtype):
self.s.str.title()
def time_upper(self, dtype):
self.s.str.upper()
def time_lower(self, dtype):
self.s.str.lower()
def time_wrap(self, dtype):
self.s.str.wrap(10)
def time_zfill(self, dtype):
self.s.str.zfill(10)
def time_isalnum(self, dtype):
self.s.str.isalnum()
def time_isalpha(self, dtype):
self.s.str.isalpha()
def time_isdecimal(self, dtype):
self.s.str.isdecimal()
def time_isdigit(self, dtype):
self.s.str.isdigit()
def time_islower(self, dtype):
self.s.str.islower()
def time_isnumeric(self, dtype):
self.s.str.isnumeric()
def time_isspace(self, dtype):
self.s.str.isspace()
def time_istitle(self, dtype):
self.s.str.istitle()
def time_isupper(self, dtype):
self.s.str.isupper()
| Methods |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 55539,
"end": 61580
} | class ____(RelocationTaskTestCase):
def setUp(self) -> None:
super().setUp()
self.relocation.step = Relocation.Step.PREPROCESSING.value
self.relocation.latest_task = OrderedTask.PREPROCESSING_COMPLETE.name
self.relocation.want_usernames = ["testuser"]
self.relocation.want_org_slugs = ["test-slug"]
self.relocation.save()
self.relocation_validation: RelocationValidation = RelocationValidation.objects.create(
relocation=self.relocation
)
def test_success(
self,
validating_poll_mock: Mock,
fake_message_builder: Mock,
fake_cloudbuild_client: Mock,
):
self.mock_cloudbuild_client(fake_cloudbuild_client, Build.Status(Build.Status.QUEUED))
self.mock_message_builder(fake_message_builder)
validating_start(self.uuid)
assert validating_poll_mock.call_count == 1
assert fake_cloudbuild_client.return_value.create_build.call_count == 1
self.relocation.refresh_from_db()
self.relocation_validation.refresh_from_db()
assert self.relocation_validation.status == ValidationStatus.IN_PROGRESS.value
assert self.relocation_validation.attempts == 1
relocation_validation_attempt = RelocationValidationAttempt.objects.get(
relocation_validation=self.relocation_validation
)
assert relocation_validation_attempt.status == ValidationStatus.IN_PROGRESS.value
def test_pause(
self,
validating_poll_mock: Mock,
fake_message_builder: Mock,
fake_cloudbuild_client: Mock,
):
self.mock_cloudbuild_client(fake_cloudbuild_client, Build.Status(Build.Status.QUEUED))
self.mock_message_builder(fake_message_builder)
self.relocation.scheduled_pause_at_step = Relocation.Step.VALIDATING.value
self.relocation.save()
validating_start(self.uuid)
assert fake_cloudbuild_client.return_value.create_build.call_count == 0
assert fake_cloudbuild_client.return_value.get_build.call_count == 0
assert fake_message_builder.call_count == 0
assert validating_poll_mock.call_count == 0
relocation: Relocation = Relocation.objects.get(uuid=self.uuid)
assert relocation.status == Relocation.Status.PAUSE.value
assert relocation.step == Relocation.Step.VALIDATING.value
assert relocation.scheduled_pause_at_step is None
assert relocation.latest_task == OrderedTask.VALIDATING_START.name
def test_retry_if_attempts_left(
self,
validating_poll_mock: Mock,
fake_message_builder: Mock,
fake_cloudbuild_client: Mock,
):
self.mock_cloudbuild_client(fake_cloudbuild_client, Build.Status(Build.Status.QUEUED))
self.mock_message_builder(fake_message_builder)
# An exception being raised will trigger a retry task.
with pytest.raises(Exception):
fake_cloudbuild_client.return_value.create_build.side_effect = Exception("Test")
validating_start(self.uuid)
assert fake_cloudbuild_client.return_value.create_build.call_count == 1
assert fake_message_builder.call_count == 0
assert validating_poll_mock.call_count == 0
relocation = Relocation.objects.get(uuid=self.uuid)
assert relocation.status == Relocation.Status.IN_PROGRESS.value
assert relocation.latest_notified != Relocation.EmailKind.FAILED.value
assert not relocation.failure_reason
def test_fail_if_no_attempts_left(
self,
validating_poll_mock: Mock,
fake_message_builder: Mock,
fake_cloudbuild_client: Mock,
):
self.relocation.latest_task = OrderedTask.VALIDATING_START.name
self.relocation.latest_task_attempts = MAX_FAST_TASK_RETRIES
self.relocation.save()
self.mock_cloudbuild_client(fake_cloudbuild_client, Build.Status(Build.Status.QUEUED))
fake_cloudbuild_client.return_value.create_build.side_effect = Exception("Test")
self.mock_message_builder(fake_message_builder)
with pytest.raises(Exception):
validating_start(self.uuid)
assert fake_cloudbuild_client.return_value.create_build.call_count == 1
assert fake_message_builder.call_count == 1
assert validating_poll_mock.call_count == 0
relocation = Relocation.objects.get(uuid=self.uuid)
assert relocation.status == Relocation.Status.FAILURE.value
assert relocation.latest_notified == Relocation.EmailKind.FAILED.value
assert relocation.failure_reason == ERR_VALIDATING_INTERNAL
def test_fail_if_max_runs_attempted(
self,
validating_poll_mock: Mock,
fake_message_builder: Mock,
fake_cloudbuild_client: Mock,
):
for _ in range(3):
RelocationValidationAttempt.objects.create(
relocation=self.relocation,
relocation_validation=self.relocation_validation,
build_id=uuid4().hex,
)
self.relocation_validation.attempts = 3
self.relocation_validation.save()
self.relocation.latest_task_attempts = MAX_FAST_TASK_RETRIES
self.relocation.save()
self.mock_cloudbuild_client(fake_cloudbuild_client, Build.Status(Build.Status.QUEUED))
self.mock_message_builder(fake_message_builder)
validating_start(self.uuid)
assert fake_cloudbuild_client.return_value.create_build.call_count == 0
assert fake_message_builder.call_count == 1
assert validating_poll_mock.call_count == 0
relocation = Relocation.objects.get(uuid=self.uuid)
assert relocation.status == Relocation.Status.FAILURE.value
assert relocation.latest_notified == Relocation.EmailKind.FAILED.value
assert relocation.failure_reason == ERR_VALIDATING_MAX_RUNS
@patch("sentry.relocation.tasks.process.CloudBuildClient")
@patch("sentry.relocation.utils.MessageBuilder")
| ValidatingStartTest |
python | kamyu104__LeetCode-Solutions | Python/checking-existence-of-edge-length-limited-paths-ii.py | {
"start": 3223,
"end": 4275
} | class ____(object):
def __init__(self, n, edgeList):
"""
:type n: int
:type edgeList: List[List[int]]
"""
edgeList.sort(key = lambda x:x[2])
self.__uf = UnionFind(n)
self.__adj = [[] for _ in xrange(n)]
for index, (i, j, weight) in enumerate(edgeList):
if not self.__uf.union_set(i, j):
continue
self.__adj[i].append((j, weight))
self.__adj[j].append((i, weight))
self.__tree_infos = TreeInfos(self.__adj)
def query(self, p, q, limit):
"""
:type p: int
:type q: int
:type limit: int
:rtype: bool
"""
if self.__uf.find_set(p) != self.__uf.find_set(q):
return False
return self.__tree_infos.max_weights(p, q) < limit
# Time: ctor: O(mlogm + m * α(n) * logm) ~= O(mlogm)
# query: O(logm + α(n) * logm) ~= O(logm)
# Space: O(n + m * α(n) + m) ~= O(n + m)
import collections
import sortedcontainers
import bisect
| DistanceLimitedPathsExist |
python | apache__airflow | airflow-core/src/airflow/callbacks/callback_requests.py | {
"start": 1129,
"end": 1777
} | class ____(BaseModel):
"""
Base Class with information about the callback to be executed.
:param msg: Additional Message that can be used for logging
"""
filepath: str
"""File Path to use to run the callback"""
bundle_name: str
bundle_version: str | None
msg: str | None = None
"""Additional Message that can be used for logging to determine failure/task heartbeat timeout"""
@classmethod
def from_json(cls, data: str | bytes | bytearray) -> Self:
return cls.model_validate_json(data)
def to_json(self, **kwargs) -> str:
return self.model_dump_json(**kwargs)
| BaseCallbackRequest |
python | walkccc__LeetCode | solutions/2570. Merge Two 2D Arrays by Summing Values/2570.py | {
"start": 0,
"end": 398
} | class ____:
def mergeArrays(self, nums1: list[list[int]],
nums2: list[list[int]]) -> list[list[int]]:
count = [0] * (1001)
self._addCount(nums1, count)
self._addCount(nums2, count)
return [[i, c] for i, c in enumerate(count) if c > 0]
def _addCount(self, nums: list[list[int]], count: list[int]) -> None:
for id_, val in nums:
count[id_] += val
| Solution |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/window.py | {
"start": 2537,
"end": 12423
} | class ____(QSplitter, SpyderConfigurationObserver):
"""Main widget to show in EditorMainWindow."""
CONF_SECTION = 'editor'
SPLITTER_WIDTH = "7px"
def __init__(self, parent, main_widget, menu_actions, outline_plugin):
super().__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
# ---- Attributes
self.editorstacks = []
self.main_widget = main_widget
self._sizes = None
# This needs to be done at this point to avoid an error at startup
self._splitter_css = self._generate_splitter_stylesheet()
# ---- Find widget
self.find_widget = FindReplace(self, enable_replace=True)
self.find_widget.hide()
# ---- Status bar
statusbar = parent.statusBar()
self.vcs_status = VCSStatus(self)
self.cursorpos_status = CursorPositionStatus(self)
self.encoding_status = EncodingStatus(self)
self.eol_status = EOLStatus(self)
self.readwrite_status = ReadWriteStatus(self)
statusbar.insertPermanentWidget(0, self.readwrite_status)
statusbar.insertPermanentWidget(0, self.eol_status)
statusbar.insertPermanentWidget(0, self.encoding_status)
statusbar.insertPermanentWidget(0, self.cursorpos_status)
statusbar.insertPermanentWidget(0, self.vcs_status)
# ---- Outline.
self.outlineexplorer = None
if outline_plugin is not None:
self.outlineexplorer = OutlineExplorerInEditorWindow(
'outline_explorer',
outline_plugin,
self,
context=f'editor_window_{str(id(self))}'
)
# Show widget's toolbar
self.outlineexplorer.setup()
self.outlineexplorer.update_actions()
self.outlineexplorer._setup()
self.outlineexplorer.render_toolbars()
# Remove bottom section actions from Options menu because they
# don't apply here.
options_menu = self.outlineexplorer.get_options_menu()
for action in ['undock_pane', 'lock_unlock_position']:
options_menu.remove_action(action)
# Signals
self.outlineexplorer.edit_goto.connect(
lambda filenames, goto, word:
main_widget.load(filenames=filenames, goto=goto, word=word,
editorwindow=self.parent())
)
self.outlineexplorer.sig_collapse_requested.connect(
lambda: self.set_conf("show_outline_in_editor_window", False)
)
# Start symbol services for all supported languages
for language in outline_plugin.get_supported_languages():
self.outlineexplorer.start_symbol_services(language)
# Tell Outline's treewidget that is visible
self.outlineexplorer.change_tree_visibility(True)
# ---- Editor widgets
editor_widgets = QWidget(self)
editor_layout = QVBoxLayout()
editor_layout.setSpacing(0)
editor_layout.setContentsMargins(0, 0, 0, 0)
editor_widgets.setLayout(editor_layout)
self.editorsplitter = EditorSplitter(
self,
main_widget,
menu_actions,
register_editorstack_cb=self.register_editorstack,
unregister_editorstack_cb=self.unregister_editorstack
)
editor_layout.addWidget(self.editorsplitter)
editor_layout.addWidget(self.find_widget)
# ---- Splitter
self.splitter = QSplitter(self)
self.splitter.setContentsMargins(0, 0, 0, 0)
if self.outlineexplorer is not None:
self.splitter.addWidget(self.outlineexplorer)
self.splitter.addWidget(editor_widgets)
self.splitter.setStretchFactor(0, 1)
self.splitter.setStretchFactor(1, 4)
# This sets the same UX as the one users encounter when the editor is
# maximized.
self.splitter.setChildrenCollapsible(False)
self.splitter.splitterMoved.connect(self.on_splitter_moved)
if (
self.outlineexplorer is not None
and not self.get_conf("show_outline_in_editor_window")
):
self.outlineexplorer.close_dock()
# ---- Style
self.splitter.setStyleSheet(self._splitter_css.toString())
def register_editorstack(self, editorstack):
logger.debug("Registering editorstack")
self.__print_editorstacks()
self.editorstacks.append(editorstack)
self.main_widget.last_focused_editorstack[self.parent()] = editorstack
# Setting attributes
editorstack.set_closable(len(self.editorstacks) > 1)
editorstack.set_outlineexplorer(self.outlineexplorer)
editorstack.set_find_widget(self.find_widget)
# Adjust style.
# This is necessary to give some space between the tabwidget pane and
# the splitter separator and borders around it.
css = PANES_TABBAR_STYLESHEET.get_copy().get_stylesheet()
css['QTabWidget::pane'].setValues(
marginLeft=f"{AppStyle.MarginSize}px",
marginRight=f"{AppStyle.MarginSize}px",
marginBottom=f"{AppStyle.MarginSize}px",
)
editorstack.tabs.setStyleSheet(css.toString())
# Signals
editorstack.reset_statusbar.connect(self.readwrite_status.hide)
editorstack.reset_statusbar.connect(self.encoding_status.hide)
editorstack.reset_statusbar.connect(self.cursorpos_status.hide)
editorstack.readonly_changed.connect(
self.readwrite_status.update_readonly)
editorstack.encoding_changed.connect(
self.encoding_status.update_encoding)
editorstack.sig_editor_cursor_position_changed.connect(
self.cursorpos_status.update_cursor_position)
editorstack.sig_refresh_eol_chars.connect(self.eol_status.update_eol)
# Register stack
self.main_widget.register_editorstack(editorstack)
def __print_editorstacks(self):
logger.debug(
f"{len(self.editorstacks)} editorstack(s) in EditorWidget:"
)
for es in self.editorstacks:
logger.debug(f" {es}")
def _generate_splitter_stylesheet(self):
# Set background color to be the same as the one used in any other
# widget. This removes what appears to be some extra borders in several
# places.
css = qstylizer.style.StyleSheet()
css.QSplitter.setValues(
backgroundColor=SpyderPalette.COLOR_BACKGROUND_1
)
# Make splitter handle to have the same size as the QMainWindow
# separators. That's because the editor and outline are shown like
# this when the editor is maximized.
css['QSplitter::handle'].setValues(
width=self.SPLITTER_WIDTH,
height=self.SPLITTER_WIDTH
)
return css
def unregister_editorstack(self, editorstack):
logger.debug("Unregistering editorstack")
self.main_widget.unregister_editorstack(editorstack)
self.editorstacks.pop(self.editorstacks.index(editorstack))
self.__print_editorstacks()
def unregister_all_editorstacks(self):
logger.debug("Unregistering all editorstacks")
for es in self.editorstacks:
es.close()
@Slot(object)
def on_window_state_changed(self, window_state):
"""
Actions to take when the parent window state has changed.
"""
# There's no need to update the Outline when the window is minimized
if window_state == Qt.WindowMinimized:
self.outlineexplorer.change_tree_visibility(False)
else:
self.outlineexplorer.change_tree_visibility(True)
def on_splitter_moved(self, position, index):
"""Actions to take when the splitter is moved."""
# There's no need to update the Outline when the user moves the
# splitter to hide it.
# Note: The 20 below was selected because the Outline can't have that
# small width. So, if the splitter position plus that amount is greater
# than the total widget width, it means the Outline was collapsed.
if (position + 20) > self.size().width():
self.outlineexplorer.change_tree_visibility(False)
else:
self.outlineexplorer.change_tree_visibility(True)
@on_conf_change(option='show_outline_in_editor_window')
def toggle_outlineexplorer(self, value):
"""Toggle outline explorer visibility."""
if value:
# When self._sizes is not available, the splitter sizes are set
# automatically by the ratios set for it above.
if self._sizes is not None:
self.splitter.setSizes(self._sizes)
# Show and enable splitter handle
self._splitter_css['QSplitter::handle'].setValues(
width=self.SPLITTER_WIDTH,
height=self.SPLITTER_WIDTH
)
self.splitter.setStyleSheet(self._splitter_css.toString())
if self.splitter.handle(1) is not None:
self.splitter.handle(1).setEnabled(True)
else:
self._sizes = self.splitter.sizes()
self.splitter.setChildrenCollapsible(True)
# Collapse Outline
self.splitter.moveSplitter(0, 1)
# Hide and disable splitter handle
self._splitter_css['QSplitter::handle'].setValues(
width="0px",
height="0px"
)
self.splitter.setStyleSheet(self._splitter_css.toString())
if self.splitter.handle(1) is not None:
self.splitter.handle(1).setEnabled(False)
self.splitter.setChildrenCollapsible(False)
| EditorWidget |
python | dask__distributed | distributed/worker_memory.py | {
"start": 2573,
"end": 14879
} | class ____:
"""Management of worker memory usage
Parameters
----------
worker
Worker to manage
For meaning of the remaining parameters, see the matching
parameter names in :class:`~.distributed.worker.Worker`.
Notes
-----
If data is a callable and has the argument ``worker_local_directory`` in its
signature, it will be filled with the worker's attr:``local_directory``.
"""
data: MutableMapping[Key, object] # {task key: task payload}
memory_limit: int | None
memory_target_fraction: float | Literal[False]
memory_spill_fraction: float | Literal[False]
memory_pause_fraction: float | Literal[False]
max_spill: int | Literal[False]
memory_monitor_interval: float
_throttled_gc: ThrottledGC
def __init__(
self,
worker: Worker,
*,
nthreads: int,
memory_limit: str | float = "auto",
# This should be None most of the times, short of a power user replacing the
# SpillBuffer with their own custom dict-like
data: WorkerDataParameter = None,
# Deprecated parameters; use dask.config instead
memory_target_fraction: float | Literal[False] | None = None,
memory_spill_fraction: float | Literal[False] | None = None,
memory_pause_fraction: float | Literal[False] | None = None,
):
self.memory_limit = parse_memory_limit(
memory_limit, nthreads, logger=worker_logger
)
self.memory_target_fraction = _parse_threshold(
"distributed.worker.memory.target",
"memory_target_fraction",
memory_target_fraction,
)
self.memory_spill_fraction = _parse_threshold(
"distributed.worker.memory.spill",
"memory_spill_fraction",
memory_spill_fraction,
)
self.memory_pause_fraction = _parse_threshold(
"distributed.worker.memory.pause",
"memory_pause_fraction",
memory_pause_fraction,
)
max_spill = dask.config.get("distributed.worker.memory.max-spill")
self.max_spill = False if max_spill is False else parse_bytes(max_spill)
if isinstance(data, MutableMapping):
self.data = data
elif callable(data):
if has_arg(data, "worker_local_directory"):
data = cast("Callable[[str], MutableMapping[Key, object]]", data)
self.data = data(worker.local_directory)
else:
data = cast("Callable[[], MutableMapping[Key, object]]", data)
self.data = data()
elif isinstance(data, tuple):
func, kwargs = data
if not callable(func):
raise ValueError("Expecting a callable")
if has_arg(func, "worker_local_directory"):
self.data = func(
worker_local_directory=worker.local_directory, **kwargs
)
else:
self.data = func(**kwargs)
elif self.memory_limit and (
self.memory_target_fraction or self.memory_spill_fraction
):
if self.memory_target_fraction:
target = int(
self.memory_limit
* (self.memory_target_fraction or self.memory_spill_fraction)
)
else:
target = sys.maxsize
self.data = SpillBuffer(
os.path.join(worker.local_directory, "storage"),
target=target,
max_spill=self.max_spill,
)
else:
self.data = {}
if not isinstance(self.data, MutableMapping):
raise TypeError(f"Worker.data must be a MutableMapping; got {self.data}")
if self.data:
raise ValueError("Worker.data must be empty at initialization time")
self.memory_monitor_interval = parse_timedelta(
dask.config.get("distributed.worker.memory.monitor-interval"),
default=False,
)
assert isinstance(self.memory_monitor_interval, (int, float))
if self.memory_limit and (
self.memory_spill_fraction is not False
or self.memory_pause_fraction is not False
):
assert self.memory_monitor_interval is not None
pc = PeriodicCallback(
# Don't store worker as self.worker to avoid creating a circular
# dependency. We could have alternatively used a weakref.
partial(self.memory_monitor, worker),
self.memory_monitor_interval * 1000,
)
worker.periodic_callbacks["memory_monitor"] = pc
self._throttled_gc = ThrottledGC(logger=worker_logger)
@log_errors
async def memory_monitor(self, worker: Worker) -> None:
"""Track this process's memory usage and act accordingly.
If process memory rises above the spill threshold (70%), start dumping data to
disk until it goes below the target threshold (60%).
If process memory rises above the pause threshold (80%), stop execution of new
tasks.
"""
# Don't use psutil directly; instead read from the same API that is used
# to send info to the Scheduler (e.g. for the benefit of Active Memory
# Manager) and which can be easily mocked in unit tests.
memory = worker.monitor.get_process_memory()
self._maybe_pause_or_unpause(worker, memory)
await self._maybe_spill(worker, memory)
def _maybe_pause_or_unpause(self, worker: Worker, memory: int) -> None:
if self.memory_pause_fraction is False:
return
assert self.memory_limit
frac = memory / self.memory_limit
# Pause worker threads if above 80% memory use
if frac > self.memory_pause_fraction:
# Try to free some memory while in paused state
self._throttled_gc.collect()
if worker.status == Status.running:
worker_logger.warning(
"Worker is at %d%% memory usage. Pausing worker. "
"Process memory: %s -- Worker memory limit: %s",
int(frac * 100),
format_bytes(memory),
(
format_bytes(self.memory_limit)
if self.memory_limit is not None
else "None"
),
)
worker.status = Status.paused
elif worker.status == Status.paused:
worker_logger.warning(
"Worker is at %d%% memory usage. Resuming worker. "
"Process memory: %s -- Worker memory limit: %s",
int(frac * 100),
format_bytes(memory),
(
format_bytes(self.memory_limit)
if self.memory_limit is not None
else "None"
),
)
worker.status = Status.running
async def _maybe_spill(self, worker: Worker, memory: int) -> None:
"""If process memory is above the ``spill`` threshold, evict keys until it goes
below the ``target`` threshold
"""
if self.memory_spill_fraction is False:
return
# SpillBuffer or a duct-type compatible MutableMapping which offers the
# fast property and evict() methods. Dask-CUDA uses this.
if not hasattr(self.data, "fast") or not hasattr(self.data, "evict"):
return
assert self.memory_limit
frac = memory / self.memory_limit
if frac <= self.memory_spill_fraction:
return
worker_logger.debug(
"Worker is at %.0f%% memory usage. Start spilling data to disk.",
frac * 100,
)
def metrics_callback(label: Hashable, value: float, unit: str) -> None:
if not isinstance(label, tuple):
label = (label,)
worker.digest_metric(("memory-monitor", *label, unit), value)
# Work around bug with Tornado 6.2 PeriodicCallback, which does not properly
# insulate contextvars. Without this hack, you would see metrics that are
# clearly emitted by Worker.execute labelled with 'memory-monitor'.So we're
# wrapping our change in contextvars (inside add_callback) inside create_task(),
# which copies and insulates the context.
async def _() -> None:
with context_meter.add_callback(metrics_callback):
# Measure delta between the measures from the SpillBuffer and the total
# end-to-end duration of _spill
await self._spill(worker, memory)
await asyncio.create_task(_(), name="memory-monitor-spill")
# End work around
async def _spill(self, worker: Worker, memory: int) -> None:
"""Evict keys until the process memory goes below the ``target`` threshold"""
assert self.memory_limit
total_spilled = 0
# Implement hysteresis cycle where spilling starts at the spill threshold and
# stops at the target threshold. Normally that here the target threshold defines
# process memory, whereas normally it defines reported managed memory (e.g.
# output of sizeof() ). If target=False, disable hysteresis.
target = self.memory_limit * (
self.memory_target_fraction or self.memory_spill_fraction
)
count = 0
need = memory - target
last_checked_for_pause = last_yielded = monotonic()
data = cast(ManualEvictProto, self.data)
while memory > target:
if not data.fast:
worker_logger.warning(
"Unmanaged memory use is high. This may indicate a memory leak "
"or the memory may not be released to the OS; see "
"https://distributed.dask.org/en/latest/worker-memory.html#memory-not-released-back-to-the-os "
"for more information. "
"-- Unmanaged memory: %s -- Worker memory limit: %s",
format_bytes(memory),
format_bytes(self.memory_limit),
)
break
weight = data.evict()
if weight == -1:
# Failed to evict:
# disk full, spill size limit exceeded, or pickle error
break
total_spilled += weight
count += 1
memory = worker.monitor.get_process_memory()
if total_spilled > need and memory > target:
# Issue a GC to ensure that the evicted data is actually
# freed from memory and taken into account by the monitor
# before trying to evict even more data.
self._throttled_gc.collect()
memory = worker.monitor.get_process_memory()
now = monotonic()
# Spilling may potentially take multiple seconds; we may pass the pause
# threshold in the meantime.
if now - last_checked_for_pause > self.memory_monitor_interval:
self._maybe_pause_or_unpause(worker, memory)
last_checked_for_pause = now
# Increase spilling aggressiveness when the fast buffer is filled with a lot
# of small values. This artificially chokes the rest of the event loop -
# namely, the reception of new data from other workers. While this is
# somewhat of an ugly hack, DO NOT tweak this without a thorough cycle of
# stress testing. See: https://github.com/dask/distributed/issues/6110.
if now - last_yielded > 0.5:
await asyncio.sleep(0)
last_yielded = monotonic()
if count:
worker_logger.debug(
"Moved %d tasks worth %s to disk",
count,
format_bytes(total_spilled),
)
def _to_dict(self, *, exclude: Container[str] = ()) -> dict:
info = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
info["data"] = dict.fromkeys(self.data)
return info
| WorkerMemoryManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 2840,
"end": 3449
} | class ____(Decoder):
"""
Decoder strategy that returns the json-encoded content of a response, if any.
"""
parameters: InitVar[Mapping[str, Any]]
def is_stream_response(self) -> bool:
return False
def decode(self, response: requests.Response) -> Generator[MutableMapping[str, Any], None, None]:
try:
document = gzip.decompress(response.content).decode("iso-8859-1")
except gzip.BadGzipFile:
document = response.content.decode("iso-8859-1")
yield from csv.DictReader(StringIO(document), delimiter="\t")
@dataclass
| GzipCsvDecoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.