How to pass parameter to a module?

Daniel Dittmar daniel.dittmar at sap.com
Thu Sep 18 13:48:32 CEST 2003


M-a-S wrote:
> I'd like to parametrize a module. That is, to set and pass
> some values into the module, while it is being imported.
> I tried this:
>
>   # sub_1.py -- main program
>   extern = "OK"
>   import sub_2
>   print sub_2.noway # prints 'no extern' :-(
>   # EOF
>
>   # sub_2.py -- parametrized module, parameter is the 'extern' var
>   try:
>      noway = extern
>   except:
>      noway = 'no extern'
>   # EOF
>
> You can guess, it doesn't work.
> How can I pass the parameter? Can I?

Create an additional module sub_2_parameters:
  # sub_1.py -- main program
  import sub_2_parameters
  sub_2_parameters.extern = "OK"
  import sub_2

  # sub_2.py -- parametrized module, parameter is the 'extern' var
  import sub_2_parameters
  try:
     noway = sub_2_parameters.extern
  except:
     noway = 'no extern'
  # EOF

Note that modules are imported only once so you cannot import sub_2 with one
set of parameters into one module and with another set of variables into
another.

Depending on your problem, it might be better to use the builtin execfile,
because you can pass a dictionary with the parameters to the call.

Daniel







More information about the Python-list mailing list