0

I have two files, in the first one where functions are defined named 'functions.py' and the second one where I can call those functions named 'test.py' and I am executing some code with exec from 'test.py' and asking it's asking for the variable initialized in 'for' loop while being 'for' loop through exec but I am getting error

NameError: name 'x' is not defined

Details:

In 'functions.py' I describe a function named 'forloop' like this:

def forloop(current, maximum, increment, code):
    frame = inspect.currentframe().f_back
    for x in range(current, maximum, increment):
        exec(str(code), frame.f_globals, frame.f_locals)

And in 'test.py' I am calling this function

from functions import *

forloop(1,5,1,"""
echo(x)
""")

Now I am executing it with another exec in another file but, I am pretty sure that problem lies in here.

I think I should be able to access 'x' from this exec but, I can't, it gives me an error saying

NameError: name 'x' is not defined

Please tell me why 'x' isn't defined and how can I get 'x' from that file.

2 Answers 2

0

first on test.py you must:

import functions

...then you can call it as

functions.forloop

cheers!

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

2 Comments

Hey, thanks for answering but, I have 'from functions import *' done this in my test.py but, it still gives the same error and I have edited my question and have added that code in question for no further confusion and please if you can help me, edit your answer.
when you use import, you import variales and functions... but not the x of a for loop. you can't use X because it is only in the for loop of forloop, if you want some output declare it in the return of your function forloop. cheers again!
0

Did you try importing the forloop method from your functions.py file into your test.py file?

Your test.py file should look something like this:

from functions import forloop

forloop(1,5,1,"""
echo(x)
""")

1 Comment

I have actually imported it like this 'from functions import *' but I thought it was obvious but, it wasn't so, I will edit my question, sorry and please do you know what else can be causing this issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.