I needed the same thing and decided to create my own to excercise on many things.
Here: primes.py
WARNING: I tried to bugfix it as much as I could and making checks on everything, but I am still an amateur, so I do NOT guarantee advanced or professional checks and absence of bugs. Use at your own risk.
It will dynamically sieve primes numbers as needed, store them in a compressed binary format and retrieve them from there.
The most useful class is 'primes'. The class itself can be used as a generator, a container, subscripted and sliced.
WARNING: be careful iterating on infinite sequences!
from primes import primes
for p in primes: # 2, 3, 5, 7, 11, ...
pass
primes[0] # 2
primes[4] # 11
primes[1:6:2] # primes object, generates 3, 7, 13
7 in primes # True
8 in primes # False
'primes also has useful methods:
primes.estimate(1000) # 7830, real 1000th prime is 7927
primes.check(7) # True
primes.index_of(11) # 4 <- primes[4] = 11
primes.count_upto(10) # 4 <- len([2,3,5,7])
primes.sieve(5, 10) # [5, 7]
primes.in_range(5, 20, 2) # primes object, generates 5, 11, 13, 19
primes.factor(12) # {2:2, 3:1} <- 12 = 2^2 * 3^1
primes.phi(6) # 6 <- Euler phi function, number of smaller co-primes
And the primes objects are themselves generator, containers, subscriptable and sliceable, but on sublists of primes:
primerange1 = primes(1, None, 2) # generator
for p in primerange1: # 3, 7, 13, 19, ...
pass
primerange1[1] # 7
primerange1[:4:-1] # generator: 13, 7, 3
2 in primerange1 # False
primerange2 = primes(6, 0, -2) # generates 13, 7, 3
len(primerange2) # 3
reversed(primerange2) # primes object, generates 3, 7, 13
The class 'plib' is used to manage the library and its settings.
I hope someone will find it useful, and I'll be glad to receive any suggestion or bug report.