[Tutor] Global var not defined?

Prasad, Ramit ramit.prasad at jpmorgan.com.dmarc.invalid
Tue Aug 27 20:34:54 CEST 2013


leam hall wrote:
> Could use some help with this. Python 2.4.3 on RHEL 5.x.
> 
> In the functions file that gets imported:
> 
> 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 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)
> 
> Error message:
> Traceback (most recent call last):
>   File "./host_tools.py", line 55, in ?
>     functions.append_customer(line_list)
>   File "/home/lhall/lang/functions.py", line 27, in append_customer
>     if len(cust) and cust not in customers:
> NameError: global name 'customers' is not defined
> 
> 

The problem is because "customers" needs to be defined
in the module with the append_customers. Global as
written refers to module level variables.

Some (possible and untested) methods to get around this are: 
1. pass in customers as an argument 
2. use globals()? 
3. add it to functions module `functions.customers = customers`.


~Ramit



This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list