# Overloading a function within a loop

**URL:** <https://discourse.julialang.org/t/overloading-a-function-within-a-loop/102615>\
**Category:** General Usage\
**Tags:** metaprogramming, itensors, itensor\
**Created:** [August 8, 2023, 8:28pm UTC](https://discourse.julialang.org/t/overloading-a-function-within-a-loop/102615 "2023-08-08T20:28:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Daniel1](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/daniel1/32/51086_2.png) [@Daniel1](https://discourse.julialang.org/u/Daniel1)\
**Post date:** [August 8, 2023, 8:28pm UTC](https://discourse.julialang.org/t/overloading-a-function-within-a-loop/102615/1 "2023-08-08T20:28:25Z")

</div>

This question is closely related to the package iTensors, but it is really a Julia programming question, no knowledge of the package is needed.

I need to overload a function provided by the package. The canonical way to do so (see [Physics (SiteType) System Examples · ITensors.jl](https://itensor.github.io/ITensors.jl/stable/examples/Physics.html)) is

```julia
ITensors.op(::OpName"Pup",::SiteType"S=1/2") = [1 0; 0 0]

```

Since I need to do this many times, I wanted to write a loop to do it. Specifically, I have a bunch of OpNames (just strings)

```julia
op_names = ["op1", "op2", "op3"]

```

and corresponding matrices (what is assigned on the right-hand side)

```julia
ops = [matrix1, matrix2, matrix3]

```

where for example `matrix1 = [1 0; 0 0]` et cetera as in the example above. So I tried the following, but this does not overload the function as expected. I’m sure I am making a mistake how exactly this should be done (scoping, evaluation, dealing with the quotation marks in the command, …)

```julia
for i in 1:length(op_names)
    name = op_names[i]
    matrix = ops[i]
    ex_string = "@eval ITensors.op(::OpName"*'"'*name*'"'*",::SiteType"*'"'*"Ququart"*'"'*") = matrix"
    eval(ex_string)
end

```

---

<div class="post-metadata">

**Author:** ![cstjean](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cstjean/32/1444_2.png) [@cstjean](https://discourse.julialang.org/u/cstjean)\
**Post date:** [August 8, 2023, 8:35pm UTC](https://discourse.julialang.org/t/overloading-a-function-within-a-loop/102615/2 "2023-08-08T20:35:19Z")

</div>

```julia
for i in 1:length(op_names)
    name = op_names[i]
    matrix = ops[i]
    @eval ITensors.op(::@OpName_str($name), ::SiteType"Ququart") = $matrix
end

```

Haven’t tried it, but it should definitely be doable with something along those lines. You basically never want to be evaluating strings.
