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

@pydef improvements #473

Merged
merged 7 commits into from
Mar 23, 2018
Merged
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
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,10 +409,14 @@ For instance,

@pyimport numpy.polynomial as P
@pydef type Doubler <: P.Polynomial
__init__(self, x=10) = (self[:x] = x)
function __init__(self, x=10)
self[:x] = x
end
my_method(self, arg1::Number) = arg1 + 20
x2.get(self) = self[:x] * 2
x2.set!(self, new_val) = (self[:x] = new_val / 2)
function x2.set!(self, new_val)
self[:x] = new_val / 2
end
end
Doubler()[:x2]

Expand Down
4 changes: 2 additions & 2 deletions src/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@ function pyio_initialize()
global pyio_initialized
if !pyio_initialized::Bool
copy!(PyIO, @pydef_object mutable struct PyIO
__init__(self, io::IO; istextio=false) = begin
function __init__(self, io::IO; istextio=false)
self[:io] = pyjlwrap_new(io) # avoid recursion
self[:istextio] = istextio
end
close(self) = @with_ioraise(close(pyio_jl(self)))
closed.get(self) = @with_ioraise(!isopen(pyio_jl(self)))
encoding.get(self) = "UTF-8"
fileno(self) = @with_ioraise(fd(pyio_jl(self)))
flush(self) = begin
function flush(self)
@with_ioraise begin
io = pyio_jl(self)
if method_exists(flush, Tuple{typeof(io)})
Expand Down
44 changes: 19 additions & 25 deletions src/pyclass.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Define new Python classes from Julia:
# Define new Python classes from Julia.
#############################################################################

import MacroTools: @capture
import MacroTools: @capture, splitdef, combinedef

######################################################################
# def_py_class definition: this is the core non-macro interface for creating
Expand All @@ -25,15 +26,13 @@ function def_py_class(type_name::AbstractString, methods::Vector;
base_classes=[], getsets::Vector=[])
# Only create new-style classes
base_classes = union(base_classes, [pybuiltin("object")])
new_type = pybuiltin("type")(type_name, tuple(base_classes...), Dict())
for (py_name, jl_fun) in methods
new_type[py_name::Symbol] = jlfun2pyfun(jl_fun::Function)
end
for (py_name, getter, setter) in getsets
new_type[py_name::Symbol] = pyproperty(jlfun2pyfun(getter),
jlfun2pyfun(setter))
end
new_type
methods = Dict(py_name => jlfun2pyfun(jl_fun::Function)
for (py_name::Symbol, jl_fun) in methods)
getter_setters = Dict(py_name => pyproperty(jlfun2pyfun(getter),
jlfun2pyfun(setter))
for (py_name::Symbol, getter, setter) in getsets)
return pybuiltin("type")(type_name, tuple(base_classes...),
merge(methods, getter_setters))
end

######################################################################
Expand Down Expand Up @@ -69,27 +68,25 @@ function parse_pydef(expr)
method_syms = Dict{Any, Symbol}() # see below
for line in lines
if !isa(line, LineNumberNode) && line.head != :line # need to skip those
@assert line.head == :(=) "Malformed line: $line"
lhs, rhs = line.args
@assert @capture(lhs,py_f_(args__)) "Malformed left-hand-side: $lhs"
def_dict = splitdef(line)
py_f = def_dict[:name]
# The dictionary of the new Julia-side definition.
jl_def_dict = copy(def_dict)
if isa(py_f, Symbol)
# Method definition
# We save the gensym to support multiple dispatch
# readlines(io) = ...
# readlines(io, nlines) = ...
# otherwise the first and second `readlines` get different
# gensyms, and one of the two gets shadowed by the other.
jl_fun_name = get!(method_syms, py_f, gensym(py_f))
jl_def_dict[:name] = get!(method_syms, py_f, gensym(py_f))
if py_f == :__init__
# __init__ must return `nothing` in Python. This is
# achieved by default in Python, but not so in Julia, so we
# special-case it for convenience.
rhs = :(begin $rhs; nothing end)
jl_def_dict[:body] = :(begin $(def_dict[:body]); nothing end)
end
push!(function_defs, :(function $jl_fun_name($(args...))
$rhs
end))
push!(methods, (py_f, jl_fun_name))
push!(methods, (py_f, jl_def_dict[:name]))
elseif @capture(py_f, attribute_.access_)
# Accessor (.get/.set) definition
if access == :get
Expand All @@ -99,14 +96,11 @@ function parse_pydef(expr)
else
error("$access is not a valid accessor; must be either get or set!")
end
jl_fun_name = gensym(Symbol(attribute,:_,access))
push!(function_defs, :(function $jl_fun_name($(args...))
$rhs
end))
dict[attribute] = jl_fun_name
dict[attribute] = jl_def_dict[:name] = gensym(Symbol(attribute,:_,access))
else
error("Malformed line: $line")
end
push!(function_defs, combinedef(jl_def_dict))
end
end
@assert(isempty(setdiff(keys(setter_dict), keys(getter_dict))),
Expand Down
25 changes: 24 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -450,10 +450,33 @@ end

# @pywith errors correctly handled
@pydef mutable struct IgnoreError
__init__(self, ignore) = (self[:ignore]=ignore)
function __init__(self, ignore)
self[:ignore] = ignore
end
__enter__(self) = ()
__exit__(self, typ, value, tb) = self[:ignore]
end

# @pydef example from README
@pydef type Doubler <: PyCall.builtin[:AssertionError]
__init__(self, x=10) = (self[:x] = x)
function my_method(self, arg1::Number)
return arg1 + 20
end
type_str(self, obj::T) where T = string(T)
x2.get(self) = self[:x] * 2
function x2.set!(self, new_val)
self[:x] = new_val / 2
end
end
d = Doubler(5)
@test d[:x] == 5
d[:x2] = 30
@test d[:x] == 15
@test d[:type_str](10) == string(Int)
@test PyCall.builtin[:isinstance](d, PyCall.builtin[:AssertionError])


@test_throws ErrorException @pywith IgnoreError(false) error()
@test (@pywith IgnoreError(true) error(); true)

Expand Down