[IPython-user] __main__ vs __main__
Fri Jan 4 04:23:41 CST 2008
On Jan 3, 2008 3:11 PM, Dave Grote <firstname.lastname@example.org> wrote:
> Hello All,
> Is there a nice way of getting ipython to use the original __main__
> rather than creating its own? In my code, I have python calling C code,
> which then calls python code, using PyRun_SimpleString. The
> PyRun_SimpleString will call, for example, a function defined in python
> before the C code is called. This works fine in plain python. But not in
> ipython - it by default creates its own name space which
> PyRun_SimpleString can't directly get at. I came up with the following,
> which seems to work ok,
> import __main__
> __main__.__name__ = "__mynamespace__"
> import IPython
> Setting __name__ is needed to prevent the ipython __main__ from being
> replaced by a FakeModule, which doesn't seem to interact with
> PyRun_SimpleString. Is this a sensible solution? Has anyone else done
> this kind of thing?
> Any and all comments welcome! Thanks!
Your approach is probably as good as I can think of, and it's why
ipython offers the user the option of providing his own execution
namespace. I know we've had plenty of problems in the past with using
the plain python __main__, which is why we resorted to the hack of
creating that whole FakeModule business. It's inelegant but it was
the only way I could find of solving certain bizarre
pickling/unpickling failures that were reported long ago.
But if you are not using pickle/unpickle in your own code (or don't
see any problems related to it), I dont' really find any fault in your
I should add that I'm not defending the whole FakeModule hackery: I'd
love to have a cleaner solution, since it does create other problems.
But so far it seems to be the lesser of several evils. Improvements
ps - it's worth noting that problems like this are to some extent
inevitable with ipython, since ipython is *itself* a (rather complex)
python program running on top of the 'real' python VM, but it's trying
very hard to 'fade into the background' so your own code appears to
live in an otherwise unmodified python VM. Sometimes, the illusion
breaks and you see the wires we're hanging from :)
More information about the IPython-user