How to access a Python global variable from C?

I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?

I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.

-------------Problems Reply------------

I'm not a python guru, but I found this question interesting so I googled around. This was the first hit on "python embedding API" - does it help?

If the attributes belong to the global scope of a module, then you can use "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get the value of an integer in the main module named "foobar", you would do the following:

PyObject *m = PyImport_AddModule("__main__");
PyObject *v = PyObject_GetAttrString(m,"foobar");

int foobar = PyInt_AsLong(v);

Py_DECREF(v);

I recommend using pyrex to make an extension module you can store the values in in python, and cdef a bunch of functions which can be called from C to return the values there.

Otherwise, much depends on the type of values you're trying to transmit.

Are you willing to modify the API a little bit?

  • You can make the C function return the new value for the global, and then call it like this:

    my_global = my_c_func(...)

  • If you're using Robin or the Python C API directly, you can pass the globals dictionary as an additional parameter and modify it
  • If your global is always in the same module, Sherm's solution looks great

For anyone coming here from Google, here's the direct method:

PyObject* PyEval_GetGlobals()

https://docs.python.org/2/c-api/reflection.html

https://docs.python.org/3/c-api/reflection.html

The return value is accessed as a dictionary.

Category:python Views:1 Time:2008-11-12
Tags: c# python

Related post

  • Python global variable insanity 2010-06-25

    You have three files: main.py, second.py, and common.py common.py #!/usr/bin/python GLOBAL_ONE = "Frank" main.py #!/usr/bin/python from common import * from second import secondTest if __name__ == "__main__": global GLOBAL_ONE print GLOBAL_ONE #Print

  • Why are local variables accessed faster than global variables in lua? 2012-02-03

    So I was reading Programing in Lua 2nd Ed and I came across this paragraph here: It is good programming style to use local variables whenever possible. Local variables help you avoid cluttering the global environment with unnecessary names. Moreover,

  • How can I access a shadowed global variable in C? 2009-03-06

    How can I access a shadowed global variable in C? In C++ I can use :: for the global namespace. --------------Solutions------------- If your file-scope variable is not static, then you can use a declaration that uses extern in a nested scope: int c;

  • Pythons global variable 2011-06-10

    Possible Duplicate: Using global variables in a function other than the one that created them How can I define a global variable. For example I have Foo1 class and Foo2 class and I want to use FooVariable in this classes as a global variable. -------

  • python global variable not working in apache 2010-06-14

    I am facing issue with the global variable, when i run in the django development server it works fine, but in apache it doesn't work here is the code below: red= "/project3/test/" def showAddRecipe(request): #global objc if "userid" in request.sessio

  • python global variable trouble 2011-01-13

    I am having troubles using global variables in python... In my program, i have declared 2 global variables, global SYNC_DATA and global SYNC_TOTAL_SIZE Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as

  • Python global variable is not working as expected 2011-04-25

    I'm just starting out with Python and experimenting with different solutions. I was working with global variables and I ran into something but don't know why it's doing what it's doing. To start, I have two modules: test1 and test2. test1 is as follo

  • dealing with python global variables when using recursive functions 2011-07-12

    I made a program that extracts the text from a HTML file. It recurses down the HTML document and returns the list of tags. For eg, input < li >no way < b > you < /b > are doing this < /li > output ['no','way','you','are'...].

  • Accessing main program global variables from a dlopen()ed dynamic library in C on OS X 2009-12-19

    I am maintaining a small application that has some plugin-like functionality, which is implemented through runtime-loaded dynamic modules. Specifically, since it's a Gtk+ app, I'm using gmodule, but the question applies to dlfcn.h / dlopen() based dy

  • how to access the correct global variable in C? 2010-01-15

    lets say I have some global var GLOBAL in main.c, but my main.c has a #include "other.h". But other.h has global var GLOBAL too. How do I let the compiler know which one I meant when I write GLOBAL in main. Is there a "this" keyword that I can use? -

  • Are Python global variables thread-safe? 2010-02-11

    edit: im asking if global variables are safe in a single-threaded web framework like tornado im using the mongoengine orm, which gets a database connection from a global variable: _get_db() # gets the db connection im also using tornado, a single-thr

  • Python Global Variable: sharing between function class then function 2010-12-05

    I'm trying to get the following global variable storage_i to be accessible to the lvl1 function, I have been able to pass it to other functions inside of the class birdofprey but I can't get it outside of that framework. I have looked around at using

  • Python global variable 2011-04-03

    def say_boo_twice(): global boo boo = 'Boo!' print boo, boo boo = 'boo boo' say_boo_twice() The output is Boo! Boo! Not as I expected. Since I declared boo as global, why is the output not: boo boo boo boo --------------Solutions------------- You've

  • Converting a program from FreeBASIC to Python: globalizing variables 2011-08-09

    In a previous post, I was told I am coding in Python like you would in BASIC (I am not "thinking" in Python yet). This is probably true and this is why I need help. This being said, I have read one book about Python so far (Bytes of Python), I bought

  • Speed of accessing local vs. global variables in gcc/g++ at different optimization levels 2011-08-30

    I found that different compiler optimization levels in gcc give quite different results when accessing a local or a global variable in a loop. The reason this surprised me is that if access to one type of variable is more optimizable than access to a

  • Accessing request as global variable in webapp2 2011-12-25

    I am migrating over my appengine application from Pylons to webapp2. In pylons the request and response objects are global. However, in webapp2 they are accessed as object attributes (self.request, self.response). But I assume using Local module in t

  • Python Global Variable Through Import? 2012-01-25

    Is this form of global variable declaration good practice in Python? My dictionary has no data in B.py in some cases. Just seems inconsistent. classes.py class Aclass: dict = {} myClass = Aclass() A.py: from classes import myClass myClass.dict["varia

  • python global variable is not saved global 2012-02-09

    NexusConnectedClients = [] class Thread1(NexusCore.Thread): def Run(): global NexusConnectedClients if(IncomingCommand == "ADDCLIENT"): NewClientOBJ = [ LastCID, ClientType, ClientADDR, ClientObject, Args[1], Args[2], '{"events":[]}' ] NexusConnected

  • Java: Problem in accessing value of global variable 2011-01-31

    Please go through the code below. String[] Info contains 2 values like this: shiftDirection & 1 or currGear & 5 and similar pairs. If I receive shiftDirection & 0, I should display the previously received value of currGear. So I create Pr

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.078 (s). 11 q(s)