How to include into local scope?

That is an error in @oxinabox’s macro. Use the one in my post instead.

I don’t.

I agree, this is just syntax. I thought you were worried about the many function arguments.

But I don’t have a problem with functions that have quite broad semantics. This happens actallually quite often with plotting functions. How many arguments (including keyword arguments) can you pass to Plots.plot?

You wrote “Currently I just copy-paste the plotting code to all places in all scripts where I need it.”

Either you are changing all of those parameters every time you run your script, in which case passing all of the keywords is an equivalent amount of handwritten code while being more readable, or you are re-using some of the parameter settings, in which case you only need to pass some of the keywords.

Look, I get it — transitioning from copy-paste code to re-usable code is hard to learn, hard to do, and hard to get into the habit of. There are no magic words we can say that will make this process easy; all we can do is to provide a few hints. And yes, one can do @include tricks in Julia to partially automate copy-and-pasting, but in the long run this is not a good substitute for re-thinking how you approach re-usable code. (I would recommend this language-agnostic book on the subject.)

8 Likes

I totally agree with you. Thank all of you for your answers!

I’m doing scientific software developing of the dirtiest kind, if you know what I mean. I have dozens of scripts that do similar but not identical things and there is a lot of MCMC, so all parameters change, but not all at once. My humble wish was just that I could do my dirty work quicker. Your macro-hack seems to be just what I wanted. If and when my code is correct and useful I will refactor it, I promise.

PS. I think @oxinabox’s macro worked before he over-engineering it.

Yes, I’m saying that is better than having all those parameters scattered across a file and not even appear together.

Syntactically, named tuples + the Parameters.jl package can be clean and have fewer errors. See 4. Arrays, Tuples, Ranges, and Other Fundamental Types — Quantitative Economics with Julia for a few examples.

1 Like

If you don’t have good defaults for these things, you can use required kwargs. Then you get the extra benefit of nice error-checking to ensure that all the variables are defined up front. And while a function with 10 positional arguments can certainly be difficult to use, there’s nothing wrong with many keyword arguments. The function call itself, then, becomes the place where you do all those assignments.

wowplot(
    x1=1:10,
    y1=rand(10),
    x2=1:10,
    y2=randn(10),
    width=3,
    height=4,
    style=:line,
    title="pretty plot",
    more="blah",
    andmore="blah",
    yetmore="blah")
3 Likes