Getfield from package / module

In a package I created, I am trying to call a function with a string, and using getfield, return a function from another package. The other package has been properly added to my package, and I could use the functions if called like a = Poisson(5)

The code below works, if I bring in the entire package with using. If I uncomment out the part of the using so only Poisson, Gamma, and Normal are allowed, then calling"Poisson") returns an error that Distributions is not defined.

I am trying to understand while restricting to those distributions won’t work but bringing in everything does.

module MYcompare
    using Distributions #: Poisson, Gamma, Normal
    export foo

    function foo(str)
        s = Symbol(str)
        f = getfield(Distributions,s)
        return f(5)


Here is what I think is the reason that Distributions is not defined:

I re-read the manual on the using statement. Specifying which names to be brought in doesn’t bring in the name of the module. Changing the code above to:

using Distributions: Distributions, Poisson, Gamma, Normal


Yes, that’s the reason.

That said, note that this usage is not idiomatic and will generate suboptimal code.

Why is it suboptimal? It looks legit.

Types won’t be inferred.


Thank you for the responses. I am using this to create a way to work with a large number of tests to compare the results between the Julia code and our in house c# so performance is not crucial. The Julia code that is eventually called follows idiomatic Julia and I think is type stable.

I’ve been using matlab for 20 years and then forced to use R for the last 5. I am in complete awe that I was able as a new user with Julia:

  • Take a TOML file generated from another system with inputs and outputs
  • Convert the TOML to a dictionary.
  • Map some of those inputs to Julia Functions (the above code)
  • Then convert the dictionary to a named tuple
  • which is then splatted as the optional arguments to a struct constructor
  • run the models/simulations with this composite type
  • compare the results of the Julia simulations to those in the TOML file

All done in a ridiculously clear and small amount of code.