0

I have this code that is throwing an error with exec, and I cant get it to work. It works when not in a function, though

def hashCheck(data):
    exec("hashes = {'hi':'hi'}")  #it was a file import before
    print(hashes['hi'])  #right here is error
    try:
        return(hashes[data]) #and here  is also error
    except KeyError:
        import hashlib
        m = hashlib.md5()
        m.update(data)
        return(m.hexdigest())
2
  • 3
    Why are you doing exec("hashes = {'hi':'hi'}") instead of hashes = {'hi':'hi'}?! Commented Dec 18, 2013 at 23:03
  • What is your python version? os? Commented Dec 18, 2013 at 23:42

1 Answer 1

1

Because your function has no assignments to hashes, python assumes when compiling it that hashes is a global variable. However, when compiling the string for exec, you do have an assignment to hashes so python assumes it is a local variable. So your exec statement assigns to a variable in the local scope, but your print statement looks for it in the global scope.

It may work if you change it to something like:

def hashCheck(data):
    hashes = None
    exec("hashes = {'hi':'hi'}")
    print(hashes['hi'])

That said, you probably shouldn't be using exec() unless you really know what you're doing and are sure you need it. If you just want some human-readable serialization for simple python objects, you may want to look into something like yaml instead.

Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly what I was looking for... I realized how bad that code was a few months later XD, but the "hashes = None" should fix the problem, ty :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.