Skip to content Skip to sidebar Skip to footer

Importing Custom Python Modules.. Why Do Only Some Elements Carry Over?

I need to create a python module that many scripts need to ultimately import from: Custom arg parsing to set format and constant args (i.e. my verbose and help args, and everythi

Solution 1:

Your previous question and code:

Fully customized Python Help Usage

With import par as pp, the all variables, classes and functions defined in that module have to be accessed with the pp. prefix. Thus pp.parser is the parser object that was created on import. pp.preq is one of the argument groups.

pp.USAGEformat is the custom formatter class. But a formatter, an object of this class is not created when the parser is created nor when par is imported. A formatter is created from the specified class when you ask for help or usage ('-h', pp.parser.print_help()).

(edit) This was wrong:

This formatter will take globals variables like version and prog from the current namespace (the importing one), not the pp one.

The formatter still takes version from the imported namespace. But I can change that with:

pp.version = '3.0'

(see my edit in https://stackoverflow.com/a/47118317/901925)

You can test this behavior in pre itself by changing version at the end of the file and doing a new print_help(). You'll see a change in the display.

pp.parser on the other hand is created on import. You could modify pp.parser.description, the attribute that was set on creation. Setting or changing pp.description doesn't do it.

When you do parser.print_help(), it calls parser.format_help, which in turn calls parser._get_formatter. That method uses parser.formatter_class to create a formatter object, which is then 'filled' and 'executed'. There's a lot of flexibility in this approach, but it can be confusing.

Post a Comment for "Importing Custom Python Modules.. Why Do Only Some Elements Carry Over?"