Julio Di Egidio <ju...@diegidio.name> writes: > On Friday, 20 August 2021 at 11:54:00 UTC+2, Loris Bennett wrote: >> Hi, >> >> TL;DR: >> >> If I have a command-line argument for a program, what is the best way >> of making this available to a deeply-nested[1] function call without >> passing the parameter through every intermediate function? > > To not pass arguments you need shared state ("global variables"): and > options in shard state, unless you have very good reasons to do > otherwise, is simply a no no.
Doesn't that slightly depend on the size of your "globe"? If a program does a few, in some sense unrelated things, and, say, only runs for a few minutes, could you not decide to make a particular parameter global, even though only one function needs it? In general, however, I would also avoid this. > <snip> >> I can see that the top-level could just create an object from a class >> which encapsulates everything, but what if I want to keep the salutation >> generation separate, so that I can have a separate program which just >> generates the salutation and print it to the terminal? > > Yes, that's basically the way to go: parse arguments into a structure (an > object) that contains all options/parameters then pass that down. Next level: > some sections of your code may require a certain subset of those options, some > may require some other, so you would structure your options object in > sub-objects for the various sets of correlated options, then rather pass just > the sub-object(s) that are relevant to the section of code you are calling. > Variations are of course possible, anyway that's the basic idea. > > Also have a look at the "argparse" library, it does all the heavy lifting for > the parsing and creation of those objects, definitely advised for in non > trivial > cases: <https://docs.python.org/3/library/argparse.html>. I am already using 'argparse' ('configargparse' actually). What aspect should I be looking at in order to produce "sub-objects"? >> I guess I am really asking how to avoid "passing through" arguments to >> functions which only need them to call other functions, so maybe the >> answer is just to avoid nesting. > > No, you don't get rid of code structure just not to pass arguments to > a function... Code may be poorly structured, but that's another > story. As I am writing new code it is more a question of imposing structure, rather than getting rid of structure. Unwritten code for a given purpose obviously has some sort of structure with regards to, say, loops and conditions, but I am less sure about the implications for how the code should be nested. Another argument against deeply-nested functions is the increased complexity of testing. Cheers, Loris -- This signature is currently under construction. -- https://mail.python.org/mailman/listinfo/python-list