I have two modules: “factors.py” and “primes.py”. In “factors.pyc”, I have a function that should find all the prime factors of a number. In it, I import 2 functions from “primes.py”. I have a dictionary in “primes.py”, which is declared as global (prior to it being defined). When I try to use it in the code of “factors.py”, I get this error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pFactors(250)
File "D:\my_stuff\Google Drive\Modules\factors.py", line 53, in pFactors
for i in primes_dict:
NameError: global name 'primes_dict' is not defined
Here are my codes:
In “factors.py”:
def pFactors(n):
import primes as p
from math import sqrt
from time import time
pFact, primes, start, limit, check, num = [], [], time(), int(round(sqrt(n))), 2, n
if p.isPrime(n):
pFact = [1, n]
else:
p.prevPrimes(limit)
for i in primes_dict:
if primes_dict[i]:
primes.append(i)
#other code
And in “primes.py”:
def prevPrimes(n):
if type(n) != int and type(n) != long:
raise TypeError("Argument <n> accepts only <type 'int'> or <type 'long'>")
if n < 2:
raise ValueError("Argument <n> accepts only integers greater than 1")
from time import time
global primes_dict
start, primes_dict, num = time(), {}, 0
for i in range(2, n + 1):
primes_dict[i] = True
for i in primes_dict:
if primes_dict[i]:
num = 2
while (num * i < n):
primes_dict[num*i] = False
num += 1
end = time()
print round((end - start), 4), ' seconds'
return primes_dict #I added this in based off of an answer on another question, but it still was unable to solve my issue
prevPrimes(n) works in the manner it was intended to. However, because I am unable to access primes_dict, pFactors(n) doesn’t work.
How can I use the dictionary primes_dict (created in one module) in another module? Thanks in advance.
Anything defined in
primeswill be under the name youimportit as. Since you imported it asp, thenprimes_dictis accessible asp.primes_dict. You could, if you wanted, doto have it as a top-level name.