# Creating the instance of a function type

**URL:** https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355
**Category:** General Usage
**Tags:** functions
**Created:** [November 6, 2024, 8:25pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355 "2024-11-06T20:25:48Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![brainandforce](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brainandforce/32/211054_2.png) [@brainandforce](https://discourse.julialang.org/u/brainandforce)
#### Post date: [November 6, 2024, 8:25pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/1 "2024-11-06T20:25:48Z")

</div>

The type of a standard Julia function `f` is `typeof(f)`, which is a singleton.

```julia-repl
julia> function f end
f (generic function with 0 methods)

julia> typeof(f)
typeof(f) (singleton type of function f, subtype of Function)

```

But it is not possible to recover the type’s sole instance with a constructor.

```julia-repl
julia> typeof(f)()
ERROR: MethodError: no method matching typeof(f)()
The type `typeof(f)` exists, but no method is defined for this combination of argument types when trying to construct it.
Stacktrace:
 [1] top-level scope
   @ REPL[6]:1

```

Is there any way to do this?

---

<div class="post-metadata">

### Author: ![raminammour](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raminammour/32/13572_2.png) [@raminammour](https://discourse.julialang.org/u/raminammour)
#### Post date: [November 6, 2024, 8:31pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/2 "2024-11-06T20:31:43Z")

</div>

Not sure what you need this for, but here you go 🙂

```julia
julia> function f end
f (generic function with 0 methods)

julia> typeof(f).instance
f (generic function with 0 methods)

julia> typeof(f).instance()
ERROR: MethodError: no method matching f()
The function `f` exists, but no method is defined for this combination of argument types.
Stacktrace:
 [1] top-level scope
   @ REPL[3]:1

julia> f()=2
f (generic function with 1 method)

julia> typeof(f).instance
f (generic function with 1 method)

julia> typeof(f).instance()
2

```

Note the subtle difference in the errors (`typeof(f)` vs `f`).

---

<div class="post-metadata">

### Author: ![brainandforce](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brainandforce/32/211054_2.png) [@brainandforce](https://discourse.julialang.org/u/brainandforce)
#### Post date: [November 6, 2024, 8:37pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/3 "2024-11-06T20:37:59Z")

</div>

Thanks - I was trying to build a data structure that represented the lazy application of a function, but I realized that it wouldn’t make much sense to do it the way I originally envisioned. At this point I’m more so interested out of curiosity.

I’m left with two questions now:

1. Is there a way to do this that doesn’t depend on using internals of the function type?
2. If not, is there some reason why constructing a function from its type is a bad idea?

---

<div class="post-metadata">

### Author: ![raminammour](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raminammour/32/13572_2.png) [@raminammour](https://discourse.julialang.org/u/raminammour)
#### Post date: [November 6, 2024, 8:42pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/4 "2024-11-06T20:42:29Z")

</div>

This [thread](https://discourse.julialang.org/t/is-there-a-way-to-get-f-from-typeof-f/18818) seems to have some clues, and I would heed the advice rather than relying on internals…

---

<div class="post-metadata">

### Author: ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)
#### Post date: [November 6, 2024, 8:43pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/5 "2024-11-06T20:43:04Z")

</div>

> [@brainandforce](#):
>
> - Is there a way to do this that doesn’t depend on using internals of the function type?
> - If not, is there some reason why constructing a function from its type is a bad idea?

No, because it might not exist! For example, `Returns` is a `Function`, but this doesn’t work:

```Julia-repl
julia> f = Returns(3)
Returns{Int64}(3)

julia> typeof(f)
Returns{Int64}

julia> f isa Function
true

julia> typeof(f).instance
ERROR: UndefRefError: access to undefined reference

```

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [November 6, 2024, 9:14pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/6 "2024-11-06T21:14:17Z")

</div>

> [@brainandforce](#):
>
> ```julia
> julia> typeof(f)()
> ERROR: MethodError: no method matching typeof(f)()
> The type `typeof(f)` exists, but no method is defined for this combination of argument types when trying to construct it.
> Stacktrace:
> [1] top-level scope
> @ REPL[6]:1
> 
> ```
> 
> Is there any way to do this?

Instead of

```julia
typeof(f)()

```

just use

```julia
f

```

The object `f` is the singleton object with type `typeof(f)` !

---

<div class="post-metadata">

### Author: ![StevenWhitaker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevenwhitaker/32/9749_2.png) [@StevenWhitaker](https://discourse.julialang.org/u/StevenWhitaker)
#### Post date: [November 6, 2024, 9:35pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/7 "2024-11-06T21:35:55Z")

</div>

The OP started out by talking about

> [@brainandforce](#):
>
> standard Julia function

which `Returns` is not; `Returns` is a `struct` that subtypes `Function`. So, I was wondering if there is an answer to the questions

> [@brainandforce](#):
>
> - Is there a way to do this that doesn’t depend on using internals of the function type?
> - If not, is there some reason why constructing a function from its type is a bad idea?

that applies to standard Julia functions specifically (besides the usual don’t rely on internals because they are not public API).

I personally think @CameronBieganek’s answer is the best answer: there is no need to use `typeof(f)` in the first place because `f` is a first-class object and can be used directly.

---

<div class="post-metadata">

### Author: ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)
#### Post date: [November 6, 2024, 10:15pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/8 "2024-11-06T22:15:02Z")

</div>

What’s a “standard Julia function?” I’m not sure I know. What about this `Returns`?

```julia-repl
julia> f = Returns(nothing)
Returns{Nothing}(nothing)

julia> typeof(f).instance # it works!
Returns{Nothing}(nothing)

```

Why should that work? Or what about a closure?

```julia-repl
julia> printer(x) = ()->println(x)
printer (generic function with 1 method)

julia> f = printer(nothing)
#printer##0 (generic function with 1 method)

julia> typeof(f).instance # it works!
#printer##0 (generic function with 1 method)

julia> f = printer(3)
#printer##0 (generic function with 1 method)

julia> typeof(f).instance # it doesn't!
ERROR: UndefRefError: access to undefined reference

```

Or what about constructors? They’re callable, too.

---

<div class="post-metadata">

### Author: ![brainandforce](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brainandforce/32/211054_2.png) [@brainandforce](https://discourse.julialang.org/u/brainandforce)
#### Post date: [November 6, 2024, 10:16pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/9 "2024-11-06T22:16:52Z")

</div>

The reason I asked this was in the case of something like

```julia
struct Foo{F<:Function}
end

```

you could not work with the stored function by instantiating it like a normal concrete type:

```julia
function bar(baz, ::Foo{F}) where F
    f = F()
    return f(baz)
end

```

Instead you’d have to do something along the lines of

```julia
struct Foo{F<:Function}
    f::F
end

function bar(baz, foo::Foo) 
    return foo.f(baz)
end

```

I was originally considering a design like this but realized it wasn’t a good idea for many reasons - in part because `f` may or may not have methods that take a single argument.

---

<div class="post-metadata">

### Author: ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)
#### Post date: [November 6, 2024, 10:33pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/10 "2024-11-06T22:33:06Z")

</div>

```julia-repl
julia> sizeof(sin)
0

julia> sizeof(Returns(nothing))
0

julia> sizeof(Returns(3))
8

```

In most cases where the function is a singleton that _can_ be retrieved from `.instance`, it also has `sizeof(F) == 0`. So while it does take up a “field” in the struct, it does not require any memory. In other words, there is no waste in using the `struct Foo{F}; f::F; end` pattern. The advantage of this format is that it also works on closures, callable structs, etc that may require additional memory.

---

<div class="post-metadata">

### Author: ![StevenWhitaker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevenwhitaker/32/9749_2.png) [@StevenWhitaker](https://discourse.julialang.org/u/StevenWhitaker)
#### Post date: [November 6, 2024, 10:37pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/11 "2024-11-06T22:37:07Z")

</div>

I was defining “standard Julia functions” as those defined with the `function` keyword (or the shortened, math-like syntax) in the top-level scope (not an inner function, not a closure, not an anonymous function). But even that definition is more nuanced than I originally thought because it includes constructors. I guess I could further restrict my definition to exclude constructors, but I think constructors are pretty “standard”. So, yeah, I see your point. I guess I was mainly wanting to provide some nuance to the conversation because I personally wouldn’t consider a callable struct a “standard Julia function”.

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [November 6, 2024, 11:35pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/12 "2024-11-06T23:35:02Z")

</div>

> [@mbauman](#):
>
> What’s a “standard Julia function?” I’m not sure I know.

Probably they mean a global function that you define with `function foo(...) ....` or equivalent, which is a singleton subtype of `Function`.

See also this thread: [How to get a function instance from a function type? - #2 by Mason](https://discourse.julialang.org/t/how-to-get-a-function-instance-from-a-function-type/79585/2) or this thread: [Instantiating function from type? - #4 by nsajko](https://discourse.julialang.org/t/instantiating-function-from-type/107532/4)

---

<div class="post-metadata">

### Author: ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)
#### Post date: [November 7, 2024, 12:24am UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/13 "2024-11-07T00:24:01Z")

</div>

Limiting ourselves to globally scoped function definitions is probably too much. We can check the public `Base.issingletontype` directly before attempting to access the internal `.instance` cache.

> [@brainandforce](#):
>
> the case of something like
> 
> ```julia
> struct Foo{F<:Function}
> end
> 
> ```
> 
> you could not work with the stored function by instantiating it like a normal concrete type:
> 
> ```julia
> function bar(baz, ::Foo{F}) where F
> f = F()
> 
> ```

This is unfeasible because `Function` subtypes are sometimes not singleton and usually intentionally remove the constructor when it is singleton. I’d say store the function as a parameter, you can do that for any `isbits` instance so “empty” singleton instances count. You just can’t annotate it like array dimensions can’t be annotated with `Int`, but you could enforce it beforehand.

```julia
julia> struct Foo{f#=isa Function=#} end

julia> Foo(f::Function) = Foo{f}()
Foo

julia> bar(baz, ::Foo{f}) where f = f(baz)
bar (generic function with 1 method)

julia> bar(25.01, Foo(sqrt))
5.000999900019995

```

The “advantage” over storing it as a possibly “empty” field `f::F` is that you still have an “empty” singleton `Foo` even when `f`’s type is not (the aforementioned closures and callable non-empty structs), though a field can store non-`isbits` instances. The choice of non-singleton support is probably down to the exact use case.

```julia
julia> (function(x); x, sizeof(x) end)(Returns(3))
(Returns{Int64}(3), 8)

julia> (function(x); x, sizeof(x) end)(Foo(Returns(3)))
(Foo{Returns{Int64}(3)}(), 0)

```

---

<div class="post-metadata">

### Author: ![raminammour](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raminammour/32/13572_2.png) [@raminammour](https://discourse.julialang.org/u/raminammour)
#### Post date: [November 7, 2024, 3:53pm UTC](https://discourse.julialang.org/t/creating-the-instance-of-a-function-type/122355/14 "2024-11-07T15:53:41Z")

</div>

I will link [Jameson’s important comment](https://discourse.julialang.org/t/is-there-a-way-to-get-f-from-typeof-f/18818/12) from that thread, and emphasize below:

> [@Is there a way to get f from typeof(f)?](https://discourse.julialang.org/t/is-there-a-way-to-get-f-from-typeof-f/18818/12):
>
> Most of the “solutions” presented here are wrong: **you should never need to access “.instance”. This is an internal API and not stable. The correct way to do this is to store the actual function object itself, and always refer to it by value and don’t try to do this in the type-domain.** Adopting the original example, we get the much-shortened:
> 
> ```julia
> julia> struct MyStruct{F}
> f::F
> end
> 
> julia> ExtractFun(s::MyStruct) = s.f
> 
> ```

What is wrong with the solution he presented, where you store the function in the struct and access it by value as above, why does it need to be done in the type domain?
