Accessing global namespace from module
John Krukoff
jkrukoff at ltgc.com
Mon Jun 11 14:06:41 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
Since the visulization software creator wasn't kind enough to bundle the
drawing functions up into a module for you, you can just do it yourself.
>>> import sys, new
>>> plotModule = new.module( 'plot' )
>>> plotModule.AddPlot = AddPlot
>>> plotModule.DrawPlots = DrawPlots
>>> sys.modules[ 'plot' ] = plotModule
Then, you can import your fake module from anywhere, and access its
contents.
>>> import plot
>>> plot
<module 'plot' (built-in)>
>>> plot.AddPlot
<function AddPlot at 0x0099E830>
Hope that helps.
---------
John Krukoff
jkrukoff at ltgc.com
More information about the Python-list
mailing list