How to write copying & pasting code macro like `include`?

I want to copy & paste some code from other files. I know there is include but I think it is to include them to module’s global scope. I uses PyCall, and to implement Pythonic class, I need to write definitions of classes in module’s __init__ function.

module A
using PyCall
const Dog = PyNULL()
function __init__()
    @pydef mutable struct _Dog
        function __init__(self, weight = 10)
            self.weight = weight
        end
        function greet(self)
            println("Bark Bark!")
        end
    end
    copy!(Dog, _Dog)
end
end

I want to move @pydef ... end to another file. It seems good to write such macro, but I don’t know what to do.

I think that structs can only be defined in the module global scope, so I am not sure if you are getting what you are expecting there.

1 Like

eval in the module’s namespace should work if you construct the expression above as an AST. See the metaprogramming chapter of the manual.

That’s true for actual struct definitions, but the @pydef macro is not actually creating a Julia struct, but creating a PyObject that’s the Python class _Dog and assigning it to the variable _Dog.

Regarding the OP’s original question: If you want to put the class definition in another file, I would recommend putting the definition inside a function, then including that file containing this function and just calling that function inside __init__. E.g., you could create a file dog.jl in the same directory as your other file containing the following:

function create_dog_class()
    @pydef mutable struct _Dog
        function __init__(self, weight = 10)
            self.weight = weight
        end
        function greet(self)
            println("Bark Bark!")
        end
    end
    return _Dog
end

Then you can do

module A
using PyCall
const Dog = PyNULL()

include("dog.jl")

function __init__()
    copy!(Dog, create_dog_class())
end
end

in your other file.

4 Likes