You could check what happens without risking to fill all available memory. You could set the memory limit explicitly:
#!/usr/bin/env python
import contextlib
import resource
@contextlib.contextmanager
def limit(limit, type=resource.RLIMIT_AS):
soft_limit, hard_limit = resource.getrlimit(type)
resource.setrlimit(type, (limit, hard_limit)) # set soft limit
try:
yield
finally:
resource.setrlimit(type, (soft_limit, hard_limit)) # restore
with limit(100 * (1 << 20)): # 100MiB
# do the thing that might try to consume all memory
i = 1
while True:
i <<= 1
This code consumes 100% CPU (on a single core) and the consumed memory grows very very slowly.
In principle, you should get MemoryError
at some point whether it happens before your computer turns to dust is unclear. CPython uses a continuous block of memory to store the digits and therefore you may get the error even if there is RAM available but fragmented.
Your specific code shouldn't trigger it but in general you could also get OverflowError
if you try to construct an integer larger than sys.maxsize
bytes.