Question regarding indirect function calls
Alex Martelli
aleax at aleax.it
Mon Apr 14 03:36:39 EDT 2003
Maxwell Hammer wrote:
> In reply to: Jack & Alex:
>
> Thanks for your advice, I did get it working using "getattr" as you
> suggested.
>
> Great! now I have another questions, since I have your attention :-)
>
> What is the most efficient way of accessing global variables across
> modules?
Just do so _explicitly_.
> I have main.py which parses a config file and sets up config values
> appropriately. Different values are required by different functions in
> other modules.
>
> I have tried defining the config values as global in main, AND in the
> other modules - but does not work (get undefine errors).
Each module's globals belong to that module only -- other modules
can access them explicitly.
> main.py:
> global config_values
> config_values = []
> ...
> load config_values
> ...
>
> Module x
> global config_values
>
> def function1():
> try to access config_values[0] fails - not found
Change to:
module x:
import main
def function1()
access main.config_values[0]
> So what I am currntly doing is passing what ever config values are needed
> through the function call
> x.function1(config_values, etc)
This is quite a good approach, too -- even more explicit.
Yet another alternative is to use "from main import config_values" in
module x, but I do NOT recommend this -- just "import main" and explicit
use of "main.config_values" is FAR better, both stylistically and in
terms of functionality. For example, with the "from" statement, you
may become vulnerable to the case in which module x is loaded before
(or worse _during_...) module main -- or to situations where at some
later point module main rebinds its config_values name to a different
value -- and so on. The "import" statement, with the explicit use of
"main.config_values", is more resilient, as well as more explicit and
thus clearer and more readable.
> How would you do this??
Probably with "import main" and using main.config_values, although
explicit arguments can also be an excellent alternative.
Alex
More information about the Python-list
mailing list