Skip to content

Commit

Permalink
Special handling for Main module
Browse files Browse the repository at this point in the history
It adds an easier way to set variables in Julia's global namespace:

>>> from julia import Main
>>> Main.xs = [1, 2, 3]
  • Loading branch information
tkf committed May 16, 2018
1 parent ee0994c commit 98c7e7e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
22 changes: 21 additions & 1 deletion julia/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ def __try_getattr(self, name):
raise AttributeError(name)


class JuliaMainModule(JuliaModule):

def __setattr__(self, name, value):
if name.startswith('_'):
super(JuliaMainModule, self).__setattr__(name, value)
else:
juliapath = self.__name__.lstrip("julia.")
setter = '''
Main.PyCall.pyfunctionret(
(x) -> eval({}, :({} = $x)),
Any,
PyCall.PyAny)
'''.format(juliapath, jl_name(name))
self._julia.eval(setter)(value)

using = property(lambda self: self._julia.using)


# add custom import behavior for the julia "module"
class JuliaImporter(object):
Expand All @@ -120,7 +137,10 @@ def __init__(self, julia):
# load module was deprecated in v3.4
def load_module(self, fullname):
juliapath = fullname.lstrip("julia.")
if isamodule(self.julia, juliapath):
if juliapath == 'Main':
return sys.modules.setdefault(fullname,
JuliaMainModule(self, fullname))
elif isamodule(self.julia, juliapath):
return sys.modules.setdefault(fullname, JuliaModule(self, fullname))
elif isafunction(self.julia, juliapath):
return getattr(self.julia, juliapath)
Expand Down
5 changes: 5 additions & 0 deletions test/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ def test_star_import_julia_module(self):
from . import _star_import
_star_import.BasicREPL

def test_main_module(self):
from julia import Main
Main.x = x = 123456
assert julia.eval('x') == x

#TODO: this causes a segfault
"""
def test_import_julia_modules(self):
Expand Down

0 comments on commit 98c7e7e

Please sign in to comment.