Atuos
Atuos

Reputation: 521

Julia: unintended extension of base functions

I have the following, incomplete Julia code:

mutable struct Env
end

function step(env, action:UInt32)
    return ones(8), 1.0, true, Dict()
end

function reset(env)
    return ones(8)
end

When I try to use it, I get the following errors:

LoadError: error in method definition: function Base.step must be explicitly imported to be extended LoadError: error in method definition: function Base.reset must be explicitly imported to be extended

I don't know what Base.step and Base.reset are, and I don't want to extend them.

Is there some way for me to keep these function names without extending the base functions? If I do just extend the base functions with my completely unrelated methods, are there going to be problems?

I really do not want to change the names of my functions because I want to keep them in line with the OpenAI Gym API.

Upvotes: 1

Views: 299

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69829

Define them inside a module like this

module Gym

mutable struct Env
end

function step(env, action::UInt32)
    return ones(8), 1.0, true, Dict()
end

function reset(env)
    return ones(8)
end

end

Then you can call them directly as step and reset inside the module. Outside the module you have to qualify them like this: Gym.step and Gym.reset.

Additionally - note that you get this problem only after you introduce step and reset in Main module before trying to extend them (e.g. by calling or referencing them). So when starting a clean Julia session this will work:

$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.2 (2018-11-08)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> step(x) = x
step (generic function with 1 method)

but this will fail:

$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.2 (2018-11-08)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> step
step (generic function with 4 methods)

julia> step(x) = x
ERROR: error in method definition: function Base.step must be explicitly imported to be extended

Upvotes: 3

Related Questions