Stream: helpdesk (published)

Topic: How to check if a method is defined for an instance?


view this post on Zulip Júlio Hoffimann (Feb 17 2021 at 13:12):

Say I have an instance obj how do I check if there is a method size(obj) defined?

view this post on Zulip Júlio Hoffimann (Feb 17 2021 at 13:13):

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.

view this post on Zulip Felix Cremer (Feb 17 2021 at 13:22):

I think, you can use hasmethod like this:

julia> hasmethod(size, (typeof(obj),))

view this post on Zulip Felix Cremer (Feb 17 2021 at 13:22):

But I am not sure, whether this is the best way to do that.

view this post on Zulip Kwaku Oskin (Feb 17 2021 at 14:00):

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?

view this post on Zulip Júlio Hoffimann (Feb 17 2021 at 14:35):

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.

view this post on Zulip Fredrik Bagge Carlson (Feb 17 2021 at 19:37):

Related discussion
https://discourse.julialang.org/t/how-much-performance-potential-does-dataframes-have/55441

view this post on Zulip Mason Protter (Feb 17 2021 at 19:48):

Note that hasmethod is slow for basically ideological reasons. If you want it to be fast, Tricks.jl has static_hasmethod.

view this post on Zulip Mason Protter (Feb 17 2021 at 19:49):

The readme even has an example of using it to define traits: https://github.com/oxinabox/Tricks.jl#uses

view this post on Zulip Júlio Hoffimann (Feb 17 2021 at 22:24):

Thank you all for the tips. Very welcome.


Last updated: Nov 22 2024 at 04:41 UTC