Reputation: 37
I am porting a library to Julia and am curious what would be considered best practice for adding Base functions from a module.
This library contains functions like values(t::MyType)
and keys(t::MyType)
that take unique struct types but do not really do the same thing or return the same types as the Base functions
What would be the best practice in this case?
Base.values(t::MyType)
and Base.keys(t::MyType)
functions so they can be used without prefixes.my_type_keys(t::MyType)
and my_type_values(t::MyType)
MyModule.values(t)
and MyModule.keys(t)
Upvotes: 1
Views: 469
Reputation: 8044
If you extend Base functions you should aim for them to do conceptually the same thing. Also, you should only extend Base functions to dispatch on types you define in your own package. The rule is that you can define methods for outside (e.g. Base or some other package's) functions for your own types. Or define you own functions for outside types. But defining methods for outside functions on outside types is "type piracy".
Given that you'd be defining them on your own types, it's not a problem that the return values differ, as long as the functions are conceptualy the same.
With regards to option 2 or 3 you can do both. Option 3 requires that you don't import the Base functions explicitly (in that case you'd be extending them by defining new methods rather than defining new functions with the same name), that you don't export them, and most likely that you'll not be using the Base functions inside your module (keys
is really widely used for example - you can use it but would have to preface it with Base.
inside the module).
Option 2 is always safe, especially if you can find a better name than my_keys
. BUT I think it is preferable to use the same name IF the function is doing conceptually the same thing, as it simplifies the user experience a lot. You can assume most users will know the Base functions and try them out if that's intuitive.
Upvotes: 5