Python Infinite Whole Elements

Python 3 integers have unlimited precision . In practice, this is limited by computer memory.

Consider the followng code:

i = 12345 while True: i = i * 123 

This obviously will not succeed. But what will be the result of this? Is all RAM (and the page file) filled with this single integer (except for the space occupied by other processes)?

Or is there any defense to catch this before he gets to this?

+5
source share
1 answer

You can check what happens without risking filling up all available memory. You can 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% of the processor (on a single core), and memory consumption is growing very slowly.

Basically, you should get a MemoryError at some point, if that happens before your computer turns to dust, it's unclear. CPython uses a continuous block of memory to store numbers , and therefore you may get an error even if there is RAM but is fragmented.

Your specific code should not run it, but overall you can also get an OverflowError if you try to build an integer larger than sys.maxsize bytes .

+1
source

All Articles