🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Method Introspection

Method introspection is counting and checking the methods of a function. It answers how many methods exist and whether a certain method exists.

A count prints as a plain number

Two methods exist for greet. The count prints as a plain number.

greet(x::Int) = "whole"
greet(x::String) = "text"
println(length(methods(greet)))

A check prints true or false

The first check asks about a whole number argument. The second check asks about a decimal argument.

greet(x::Int) = "whole"
greet(x::String) = "text"
println(hasmethod(greet, (Int,)))
println(hasmethod(greet, (Float64,)))

Adding a method raises the count

One method exists at first. Adding a second method raises the count to two.

greet(x::Int) = "whole"
println(length(methods(greet)))
greet(x::String) = "text"
println(length(methods(greet)))

Example

describe(x::Int) = "whole"
describe(x::String) = "text"
println(length(methods(describe)))
println(hasmethod(describe, (Int,)))
println(hasmethod(describe, (Float64,)))
println(describe(7))

Key points

  • Method count: length(methods(f)) gives the number of methods of f as a plain number.
  • Method check: hasmethod tells whether a function accepts a given set of argument types.
  • Tuple of types: the second argument to hasmethod is a tuple of argument types.
  • Growing count: adding a method raises the count by one.
  • Use length and hasmethod to check a function before calling it in a new way.

In this example, two methods exist for describe. The count prints two. Two checks print true and false. A final call prints its result.

Note

print a count or a true or false result, never a whole methods table.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

greet has methods for Int and String. What does length(methods(greet)) print?