[Tutor] global is bad but ...
Kent Johnson
kent37 at tds.net
Wed Nov 14 13:53:45 CET 2007
Dinesh B Vadhia wrote:
> Alan/Jim:
>
> It's good to hear some pragmatic advice.
>
> This particular module has 8 small functions that share common data
> (structures, primarily in arrays and vectors). I tried passing array_G
> as a parameter but that doesn't work because everything in the function
> remains local and I cannot get back the altered data (unless you know
> better?).
That sounds like a good candidate for a class with array_G as an
instance attribute and your 8 small functions as methods.
If you pass the array as a parameter, you can change the passed
parameter in place and changes will be seen by other clients.
Re-assigning the parameter will have only local effect. For example:
This function mutates the list passed in, so changes are visible externally:
In [23]: def in_place(lst):
....: lst[0] = 1
....:
....:
In [24]: a = [3,4,5]
In [25]: in_place(a)
In [26]: a
Out[26]: [1, 4, 5]
This function assigns a new value to the local name, changes are not
visible externally:
In [27]: def reassign(lst):
....: lst = []
....:
....:
In [28]: reassign(a)
In [29]: a
Out[29]: [1, 4, 5]
This function replaces the contents of the list with a new list. This is
a mutating function so the changes are visible externally.
In [30]: def replace(lst):
....: lst[:] = [1,2,3]
....:
....:
In [31]: replace(a)
In [32]: a
Out[32]: [1, 2, 3]
> The 'global' route works a treat so far.
Yes, globals work and they appear to be a simple solution, that is why
they are used at all! They also
- increase coupling
- hinder testing and reuse
- obscure the relationship between pieces of code
which leads experienced developers to conclude that in general globals
are a bad idea and should be strenuously avoided.
Kent
More information about the Tutor
mailing list