Python file structure
zljubisicmob at gmail.com
zljubisicmob at gmail.com
Tue May 12 15:58:54 EDT 2015
On Tuesday, May 12, 2015 at 9:49:20 PM UTC+2, Ned Batchelder wrote:
> On Tuesday, May 12, 2015 at 3:13:32 PM UTC-4, zljubi... at gmail.com wrote:
> > Hi, I have python file with the following structure:
> >
> > import...
> >
> > A = configparser.get(...)
> > B = configparser.get(...)
> >
> > Command line parameters parsing [they can change variable A or B]
> >
> > Def usage()
> > Print how to use script parameters
> >
> > def main():
> > ...
> >
> > if __name__ == "__main__":
> > main()
> >
> > If I find an error in command line parameters section I cannot call function usage() because it is not defined yet.
> >
> > I have few options here:
> > 1. Put definition of usage function before command line parameters parsing section
> > 2. Make parameters global and put them in the main function
> > 3. ...maybe some other options...
> >
>
> I would put all of the code into a function some place. Don't have
> anything at the top level of the file except imports, function (and
> class) definitions, and an "if __name__....." clause at the bottom.
>
> If you need to use globals, assign them inside a parse_arguments
> function that has a "global" statement in it.
>
> This advice is consistent with Chris' "define things before they
> are used." It does it by defining everything before anything is
> run.
>
> As a side note, if you are going to have code at the top-level of
> the file, then there's no point in the "if __name__..." clause.
> That clause is designed to make a file both runnable and importable.
> But your top-level code makes the file very difficult to import.
>
> --Ned.
It makes sense. The only drawback is that variables are global so they could be changed anywhere in the program.
I also agree that it is more python approach.
Thanks to both of you.
More information about the Python-list
mailing list