Skip to content

Commit 9b459a8

Browse files
author
Christopher Doris
committed
adds juliacall.using
1 parent 383e366 commit 9b459a8

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

docs/src/juliacall.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,30 @@ and will ensure the given packages are installed.
9898

9999
## Utilities
100100

101+
`````@customdoc
102+
juliacall.using - Function
103+
104+
```python
105+
using(globals, module, attrs=None, prefix='jl', rename=None)
106+
```
107+
108+
Import the Julia `module` into `globals`.
109+
110+
If `attrs` is given, the given attributes are imported from the module instead of the
111+
module itself. It may be a list of strings or a space-separated string.
112+
113+
Each item imported is renamed before being added to `globals`. By default a `prefix` is
114+
added. You more generally supply a `rename` function which maps a string to a string.
115+
116+
In the following example we import some items from `Base` to do some vector operations:
117+
```python
118+
juliacall.using(locals(), 'Base', 'Vector Int push! pop!', rename=lambda x:'jl'+x.replace('!',''))
119+
x = jlVector[jlInt]()
120+
jlpush(x, 1, 2, 3)
121+
jlpop(x) # 3
122+
```
123+
`````
124+
101125
`````@customdoc
102126
juliacall.newmodule - Function
103127

python/juliacall/__init__.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,42 @@ def newmodule(name):
77
"A new module with the given name."
88
return Base.Module(Base.Symbol(name))
99

10+
def using(globals, module, attrs=None, prefix='jl', rename=None):
11+
"""Import a module into globals.
12+
13+
Args:
14+
globals: A dict to import into (usually 'locals()').
15+
module: The name of the module to import.
16+
attrs: If given, import these attributes from the module instead of
17+
the module itself. A list of strings or a space-separated string.
18+
prefix: A prefix added to the name of each imported item.
19+
rename: If given, a function mapping names to the name assigned in globals.
20+
"""
21+
# rename
22+
if rename is None:
23+
rename = lambda name: prefix + name
24+
# import the module
25+
path = module.split('.')
26+
mname = path[0]
27+
if mname == 'Base':
28+
module = Base
29+
elif mname == 'Core':
30+
module = Core
31+
elif mname == 'Main':
32+
module = Main
33+
else:
34+
module = Base.require(Base.Main, Base.Symbol(mname))
35+
for attr in path[1:]:
36+
module = Base.getproperty(module, Base.Symbol(attr))
37+
# export
38+
if attrs is None:
39+
globals[rename(path[-1])] = module
40+
else:
41+
if isinstance(attrs, str):
42+
attrs = attrs.split()
43+
for attr in attrs:
44+
globals[rename(attr)] = getattr(module, attr)
45+
1046
class As:
1147
"Interpret 'value' as type 'type' when converting to Julia."
1248
__slots__ = ("value", "type")

0 commit comments

Comments
 (0)