[Tutor] Global var not defined?

Alan Gauld alan.gauld at btinternet.com
Tue Aug 27 20:34:23 CEST 2013


On 27/08/13 18:58, leam hall wrote:

> def append_customer(line_list):
>          global customers
>          cust = line_list[0]     // list with Customer info in [0]
>          cust = clean_word(cust)  // Trims white space
>
>          if len(cust) and cust not in customers:
>                  host_list[cust] = {}
>                  customers.append(cust)

In Python global only applies to the local file.
Thus customers needs to be at the global level in
functions.py.

But since its a bad use of globals it would be better to just get the 
function to return the value and do the append in the top level file...

BTW the line

 >                  host_list[cust] = {}

Makes no sense since you are  adding an empty dictionary  to a variable 
that doesn't exist so you should get an error. I assume you have 
simplified the code somewhat?

> In the calling file:
>
> import functions
> import sys
>
> customers = []
> .
> .
> for line in input_file:
>      line = line.strip()
>      if not len(line):
>          continue
>      line_list = line.split(',')
>      functions.append_customer(line_list)

        customers.append(functions.get_customer(line_list, customers))

Avoids any need for globals.

Personally I'd move the line split into the function so your loop looks 
like:

for line in input_file:
      line = line.strip()
      if line:
         customers.append(functions.get_customer(line_list, customers))

Alternatively I'd put the customers list into a module called customer
and move the customer functions into that module. And then it looks
like I might have a Customer class emerging... And maybe the code above 
would become a class method:
    Customer.readFromFile(aFile) -> [cust1, cust2, ...]


Just a thought...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list