Accessing global namespace from module

kyosohma at gmail.com kyosohma at gmail.com
Mon Jun 11 13:37:49 EDT 2007


On Jun 11, 11:02 am, reubendb <reube... at gmail.com> wrote:
> Hello,
> I am new to Python. I have the following question / problem.
> I have a visualization software with command-line interface (CLI),
> which essentially is a Python (v. 2.5) interpreter with functions
> added to the global namespace. I would like to keep my own functions
> in a separate module and then import that module to the main script
> (that will be executed using the CLI interpreter). The problem is, I
> cannot access the functions in the global namespace of the main script
> from my module. Is there anyway to do that ?
>
> Here is an example of what I meant. The function AddPlot() and
> DrawPlots() are added to the global namespace by the software CLI. If
> I do this:
>
> mainscript.py:
> ---------------------------
> AddPlot("scatter", "coordinate")
> # set other things here
> DrawPlots()
>
> it works fine. But I want to be able to do this:
>
> myModule.py:
> ----------------------
> def defaultScatterPlot():
>   AddPlot("scatter", "coordinate")
>   #do other things
>   DrawPlots()
>
> and then in mainscript.py:
> ---------------------------------------
> import myModule
> myModule.defaultScatterPlot()
>
> This won't work because myModule.py doesnot have access to AddPlot().
> How do I do something like this ?
>
> Thank you in advance for any help.
> RDB

I think you're doing it backwards. If you want access to AddPlot, then
you should import mainscript into that module instead of the other way
around. When I have common methods I want to call from different
scripts, I put those methods/functions into their own module/file.
Then I just import the module and call whatever script I need.

<code>

commonMods.py
---------------------
AddPlot(*args, *kwargs):
    # Do something
DrawPlots(*args, *kwargs):
    # Do something
---------------------


mainProgram.py
------------------------
from commonMods import AddPlot
AddPlot("scatter", "coordinate")
# etc etc
-------------------------

myModule.py
------------------------
from commonMods import AddPlot
AddPlot("scatter", "coordinate")
# etc etc
-------------------------

</code>

Hope that helps.

Mike




More information about the Python-list mailing list