Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More flexible pyimport syntax. Fixes #66 #329

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ compare it to the built-in Julia `sin`:
@pyimport math
math.sin(math.pi / 4) - sin(pi / 4) # returns 0.0

# Alternative syntax
@pyimport math: (pow, radians)
pow(radians(180), 2) # returns pi²

Type conversions are automatically performed for numeric, boolean,
string, IO stream, date/period, and function types, along with tuples,
arrays/lists, and dictionaries of these types. (Python functions can
Expand Down
77 changes: 68 additions & 9 deletions src/PyCall.jl
Original file line number Diff line number Diff line change
Expand Up @@ -419,19 +419,78 @@ function pyimport_name(name, optional_varname)
end
end

macro pyimport(name, optional_varname...)
mname = modulename(name)
Name = pyimport_name(name, optional_varname)
quote
if !isdefined($(Expr(:quote, Name)))
const $(esc(Name)) = pywrap(pyimport($mname))
elseif !isa($(esc(Name)), Module)
error("@pyimport: ", $(Expr(:quote, Name)), " already defined")
# Helper for pyimport
function pyimport_object_or_submodule(mod, member)
try
# Try to import member as a submodule of `mod`
return pywrap(pyimport(mod[:__name__] * "." * string(member)))
catch e
# Then it must be a variable/function
if isa(e, PyCall.PyError)
return mod[member]
else
rethrow()
end
nothing
end
end

"""
`@pyimport` imports a Python module. Examples:

```julia
@pyimport scipy
@pyimport scipy.stats: (betaprime, distributions) # note the parentheses
@pyimport scipy.stats as sstats

println(scipy.average([1,2,3]))
```
"""
macro pyimport(expr, optional_varname...)
if isa(expr, Expr)
# We could support `@pyimport module: a, b` but it's awkward because
# it parses as `((module:a), b)
@assert expr.head != :tuple "@pyimport requires parentheses, eg. @pyimport module_name: (a, b)"
end
if @capture(expr, mod_sym_:what_)
# Handle `@pyimport module_name: (a, b, c)`
@assert isempty(optional_varname) "Bad @pyimport syntax. See ?@pyimport"
if isa(what, Symbol)
members = [what]
else
@assert @capture(what, ((members__),)) "Bad @pyimport statement"
end
mod = gensym()
esc(quote
$mod = $PyCall.pyimport($(modulename(mod_sym)))
$([quote
if !isdefined($(Expr(:quote, member)))
const $member =
$PyCall.pyimport_object_or_submodule($mod, $(Expr(:quote, member)))
elseif !isa($member, Union{Module, PyObject})
error("Cannot @pyimport ", $(Expr(:quote, member)),
". It is already defined in the current module.")
end
end
for member in members]...)
nothing
end)
else
# Handle `@pyimport module_name` and `@pyimport module_name as bar`
mname = modulename(expr)
name = pyimport_name(expr, optional_varname)
quote
if !isdefined($(Expr(:quote, name)))
const $(esc(name)) = pywrap(pyimport($mname))
elseif !isa($(esc(name)), Module)
error("Cannot @pyimport ", $(Expr(:quote, name)),
". It is already defined in the current module.")
end
nothing
end
end
end


#########################################################################

"""
Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ array2py2arrayeq(x) = PyCall.py2array(Float64,PyCall.array2py(x)) == x
@pyimport math
@test_approx_eq math.sin(3) sin(3)

@pyimport math: (pow, radians)
@test_approx_eq pow(radians(180), 2) pi ^ 2

@test collect(PyObject([1,"hello",5])) == [1,"hello",5]

@test try @eval (@pyimport os.path) catch ex isa(ex, ArgumentError) end
Expand Down