MCPcopy Index your code
hub / github.com/python/mypy / KeepAlive

Class KeepAlive

mypyc/ir/ops.py:1821–1866  ·  view source on GitHub ↗

A no-op operation that ensures source values aren't freed. This is sometimes useful to avoid decref when a reference is still being held but not seen by the compiler. A typical use case is like this (C-like pseudocode): ptr = &x.item r = *ptr keep_alive x # x must n

Source from the content-addressed store, hash-verified

1819
1820@final
1821class KeepAlive(RegisterOp):
1822 """A no-op operation that ensures source values aren't freed.
1823
1824 This is sometimes useful to avoid decref when a reference is still
1825 being held but not seen by the compiler.
1826
1827 A typical use case is like this (C-like pseudocode):
1828
1829 ptr = &x.item
1830 r = *ptr
1831 keep_alive x # x must not be freed here
1832 # x may be freed here
1833
1834 If we didn't have "keep_alive x", x could be freed immediately
1835 after taking the address of 'item', resulting in a read after free
1836 on the second line.
1837
1838 If 'steal' is true, the value is considered to be stolen at
1839 this op, i.e. it won't be decref'd. You need to ensure that
1840 the value is freed otherwise, perhaps by using borrowing
1841 followed by Unborrow.
1842
1843 Be careful with steal=True -- this can cause memory leaks.
1844 """
1845
1846 error_kind = ERR_NEVER
1847
1848 def __init__(self, src: list[Value], line: int = -1, *, steal: bool = False) -> None:
1849 super().__init__(line)
1850 assert src
1851 self.src = src
1852 self.steal = steal
1853
1854 def sources(self) -> list[Value]:
1855 return self.src.copy()
1856
1857 def stolen(self) -> list[Value]:
1858 if self.steal:
1859 return self.src.copy()
1860 return []
1861
1862 def set_sources(self, new: list[Value]) -> None:
1863 self.src = new[:]
1864
1865 def accept(self, visitor: OpVisitor[T]) -> T:
1866 return visitor.visit_keep_alive(self)
1867
1868
1869@final

Callers 8

keep_aliveMethod · 0.90
flush_keep_alivesMethod · 0.90
get_type_of_objMethod · 0.90
_py_vector_callMethod · 0.90
new_list_opMethod · 0.90
builtin_lenMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…