how to embed ipython 0.12 so that it inherits namespace of the caller? - embed

EDIT I isolated a real minimal example which does not work (it is a part of more complex code); the culprit is the inputhook part after all:
def foo():
exec 'a=123' in globals()
from IPython.frontend.terminal.embed import InteractiveShellEmbed
ipshell=InteractiveShellEmbed()
ipshell()
# without inputhook, 'a' is found just fine
import IPython.lib.inputhook
IPython.lib.inputhook.enable_gui(gui='qt4')
foo()
Running with 0.12:
In [1]: a
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/tmp/<ipython-input-1-60b725f10c9c> in <module>()
----> 1 a
NameError: name 'a' is not defined
What would be the way around?

The problem is due to this call to InteractiveShell.instance() in the qt integration, when called before IPython is initialized. If this is called before your embedded shell is created, then some assumptions are not met. The fix is to create your embedded shell object first, then you shouldn't have any issue. And you can retrieve the same object from anywhere else in your code by simply calling InteractiveShellEmbed.instance().
This version should work just fine, by creating the InteractiveShellEmbed instance first:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# create ipshell *before* calling enable_gui
# it is important that you use instance(), instead of the class
# constructor, so that it creates the global InteractiveShell singleton
ipshell = InteractiveShellEmbed.instance()
import IPython.lib.inputhook
IPython.lib.inputhook.enable_gui(gui='tk')
def foo():
# without inputhook, 'a' is found just fine
exec 'a=123' in globals()
# all calls to instance() will always return the same object
ipshell = InteractiveShellEmbed.instance()
ipshell()
foo()

Related

Julia Module calling User Defined Function

I have a module which builds up some levels of abstraction for a simulation I'd like to perform. Let's say the lowest level of abstraction is a node (which we build into systems, if we truncate this at two levels of abstraction), which is a subtype of an abstract type I define in the module. The nodes are updated with a user-defined update! function.
I want the user to be able to define a new node and update! function, but the update! function should be callable from the module's system_update! function. An example is provided below:
module test_pack
abstract type Node end
struct System{N<:Node}
nodes::Array{N,1}
end
function system_update!(s::System)
update!.(s.nodes)
end
export Node, System, system_update!
end
# import module
using Main.test_pack
# User-defined types and functions
mutable struct My_Node<:Node
state
end
function update!(n::My_Node)
n.state *= 2
end
# Define system of user defined nodes
sys = System([My_Node(1), My_Node(2)])
# Run the system
system_update!(sys)
Running this code gives
ERROR: LoadError: UndefVarError: update! not defined
However, if I move the definition of My_Node and update! to within the module and then export My_Node, the code executes and return the appropriate 2,4 output.
Is there a way I can enable the type of behavior I expect, where the user defines the type and update! function, but the module-defined System can call those functions?
One way of doing what you want would be to set things up in such a way that the update! function is defined by the module, and the code which defines the My_Node type (deriving from Node) also defines a specific method extending the update! function.
Here, since there is no default implementation for update! working on an argument of abstract type Node, an empty generic function can be defined to only mark the function as "belonging" to the module, without providing any implementation.
The implementation of the TestPack.update!(::My_Node) method explicitly extends this function, referring to it via a fully qualified name.
module TestPack
abstract type Node end
struct System{N<:Node}
nodes::Array{N,1}
end
function update! end
function system_update!(s::System)
update!.(s.nodes)
end
export Node, System, system_update!
end
# import module
using .TestPack
# User-defined types and functions
mutable struct My_Node<:Node
state
end
function TestPack.update!(n::My_Node)
n.state *= 2
end
sys = System([My_Node(1), My_Node(2)])
# Run the system
system_update!(sys)
The code above runs without problem and yields:
julia> sys
System{My_Node}(My_Node[My_Node(2), My_Node(4)])
As an aside, note that it is customary in Julia to use CamelCase notations for the name of modules; in the example above, I renamed your module to TestPack to follow this stylistic convention.
The module can also be referred to as using .TestPack instead of using Main.TestPack; this is called a relative module path.

Error accessing a module function

I have a problem with basic module usage in Lua. I have one file "helloworld.lua" and a second file "main.lua". I would like to call a function from the first file inside the second file. But I am getting an error:
attempt to call field 'printText' (a nil value)
My actual code is below. Can someone tell me where the problem is?
helloworld.lua
local module = {}
function module.printText()
print("Hello world")
end
return module
main.lua
hello = require("helloworld")
hello.printText()
As mentioned in the comments, this is the right way to do it. This could be a problem if there is a conflicting helloworld module, or if you have a running lua state and are modifying the files without starting a new one.
require will only load the module passed with a string once. Check package.loaded["helloworld"]. You can set this to nil so that require will load the file again:
package.loaded["helloworld"] = nil
hello = require("helloworld") -- will load it for sure

How to run a function in another process using Cython (and not interacting with Python)? [Included Python code example]

What is the best way to replicate the below behavior in a cython (without having to interact with Python)? Assuming that the function which will be passed into the new process is a cdef function.
import time
from multiprocessing import Process
def func1(n):
while True:
# do some work (different from func2)
time.sleep(n)
def func2(n):
while True:
# do some other work (different from func1)
time.sleep(n)
p1 = Process(target=func1, args=(1,))
p1.start()
p2 = Process(target=func2, args=(1,))
p2.start()
How to run a function in another process using Cython (without interacting with Python)?

Julia has some import exception mechanism?

In Python we can do:
try:
import foo
# do stuff
except ImportError:
print("Consider installing package 'foo' for full functionality.")
Is it possible to catch a similar exception in Julia?
At this time Julia doesn't have an import exception mechanism, and you can't put using inside a try-catch block.
In the comments on this answer, the question is refined to really ask how to do conditional includes. Here is an example of how to do that:
# We are making a module that conditionally includes ImageView
module MyModule
# Optional plotting features using ImageView
# The view function is defined in ImageView
export view # Re-export ImageView.view (optional)
try
require("ImageView") # Will throw error if ImageView not installed
global view(args...) = Main.ImageView.view(args...)
catch
# Needs global to put it in the module scope, not the catch scope
global view(args...) = error("ImageView.jl required for drawing!")
# Alternatively, global view(args...) = nothing
end
# ....
end

Python3: Use a variable defined within a function

I am confused over this behavior seen in Python3 and I was wondering if there is a way around it or if I am doing something wrong.
I have seen this in the command-line and scripts. I define a function called "SETVAR()". SETVAR() will use getpass.getuser() (which was imported) and save the output to the variable USER. The function is executed, but when USER is printed, I get an error stating the variable was not defined. If I define the variable outside of a function, all is well. However, in my scripts, I want to use variables defined and made in a function. Can it be done?
>>> def SETVAR():
... USER = getpass.getuser()
...
>>> SETVAR()
>>> print(USER)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'USER' is not defined
>>> USER = getpass.getuser()
>>> print(USER)
collier
Question: How do I use variables defined and created in functions that have been defined and executed whether in the command-line or script?
Even if you define and create the variable inside a function, you can let Python know that you want the resulting variable to be globally accessible;
>> def SETVAR():
... global USER
... USER='olle'
...
>>> SETVAR()
>>> print(USER)
olle
>>>
EDIT: I tend to agree with #Wooble in the comments that this is something you may want to think twice about using in most circumstances. For simple scripts it can be very useful, but for more complex situations it can make the code hard to follow.