Say I have an instance obj
how do I check if there is a method size(obj)
defined?
I would like to write a function that behaves differently depending on this availability of size. I know this is a trait, but I wonder if there is a simple way of checking this without relying on packages.
I think, you can use hasmethod like this:
julia> hasmethod(size, (typeof(obj),))
But I am not sure, whether this is the best way to do that.
Sorry, just to avoid XY problem. How is it possible that method size
for object
is not defined? I mean, it's you as a developer who is writing code and you know exactly whether you wrote this method or not. Why determine it in runtime?
I would like to check if the user provided type has support for size, and if it has I can specialize the implementation. This is pretty much a trait but since Julia doesn't support traits as a built-in I think the hasmethod is enough in this case.
Related discussion
https://discourse.julialang.org/t/how-much-performance-potential-does-dataframes-have/55441
Note that hasmethod
is slow for basically ideological reasons. If you want it to be fast, Tricks.jl has static_hasmethod
.
The readme even has an example of using it to define traits: https://github.com/oxinabox/Tricks.jl#uses
Thank you all for the tips. Very welcome.
Last updated: Nov 06 2024 at 04:40 UTC