Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8522257
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T07:04:14+00:00 2026-06-11T07:04:14+00:00

The Python C API function PyEval_EvalCode let’s you execute compiled Python code. I want

  • 0

The Python C API function PyEval_EvalCode let’s you execute compiled Python code. I want to execute a block of Python code as if it were executing within the scope of a function, so that it has its own dictionary of local variables which don’t affect the global state.

This seems easy enough to do, since PyEval_EvalCode lets you provide a Global and Local dictionary:

PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)

The problem I run into has to do with how Python looks up variable names. Consider the following code, that I execute with PyEval_EvalCode:

myvar = 300
def func():
    return myvar

func()

This simple code actually raises an error, because Python is unable to find the variable myvar from within func. Even though myvar is in the local dictionary in the outer scope, Python doesn’t copy it into the local dictionary in the inner scope. The reason for this is as follows:

Whenever Python looks up a variable name, first it checks locals, then it checks globals, and finally it checks builtins. At module scope, locals and globals are the SAME dictionary object. So the statement x = 5 at module scope will place x in the the locals dictionary, which is also the globals dictionary. Now, a function defined at module scope which needs to lookup x won’t find x within the function-scope locals, because Python doesn’t copy module-scope locals into function-scope locals. But this normally isn’t a problem, because it can find x in globals.

x = 5
def foo():
   print(x) # This works because 'x' in globals() == True

It’s only with nested functions, that Python seems to copy outer-scope locals into inner-scope locals. (It also seems to do so lazily, only if they are needed within the inner scope.)

def foo():
   x = 5
   def bar():
      print(x) # Now 'x' in locals() == True
   bar()

So the result of all this is that, when executing code at module scope, you HAVE to make sure that your global dictionary and local dictionary are the SAME object, otherwise module-scope functions won’t be able to access module-scope variables.

But in my case, I don’t WANT the global dictionary and local dictionary to be the same. So I need some way to tell the Python interpreter that I am executing code at function scope. Is there some way to do this? I looked at the PyCompileFlags as well as the additional arguments to PyEval_EvalCodeEx and can’t find any way to do this.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T07:04:15+00:00Added an answer on June 11, 2026 at 7:04 am

    Python doesn’t actually copy outer-scope locals into inner-scope locals; the documentation for locals states:

    Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

    Here “free” variables refers to variables closed over by a nested function. It’s an important distinction.

    The simplest fix for your situation is just to pass the same dict object as globals and locals:

    code = """
    myvar = 300
    def func():
        return myvar
    
    func()
    """
    d = {}
    eval(compile(code, "<str>", "exec"), d, d)
    

    Otherwise, you can wrap your code in a function and extract it from the compiled object:

    s = 'def outer():\n    ' + '\n    '.join(code.strip().split('\n'))
    exec(compile(s, '<str>', 'exec').co_consts[0], {}, {})
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following python code using the twisted API. def function(self,filename): def results(result):
I'm using a Python API that expects me to pass it a function. However,
The question How do I call svn_client_list2 C API function from python via SVN
I have an app that uses the python/c api and I was wondering what
I try to use checkContour() function in new python api (cv2) and it do
How can I simulate the following Python function using the Python C API? def
I am programing VIX API from python 2.5, but now I want to port
I'm having trouble using python function decorators in Google's AppEngine. I'm not that familiar
From the c-api, I would like to call a python function by name. I
I've discovered a function in the Python C API named PyEval_CallFunction which seems to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.