[Tutor] Global var not defined?

Alan Gauld alan.gauld at btinternet.com
Wed Aug 28 00:03:37 CEST 2013


On 27/08/13 19:50, leam hall wrote:
> Well, I'm happy to change things but my python is only so good. And much
> of that is based off of shell programming.
>

You will need to change something because what you have won;t work.

The question is what to change?

> What the data looks like is fairly simple. I have a spreadsheet of host
> information. Customer 'Alan' may have a dozen or so servers and customer
> Ramit has another dozen or two.

So abstracting that you have several customer objects each containing
a list(or dict?) of servers. Servers in turn have numerous attributes:
name, role, ip, environ etc...

> When I print these out they will be
> sorted by customer but rolled into a single file.

So the customer objects have a method that prints to a file.

That's the OOP approach, but you can do it without classes
if you want, its just a bit more effort on the readability
and coding front.

> The line "host_list[cust] = {}" creates the customer dictionary if that
> customer doesn't exist.

It may be better to look at the get() method of dictionaries for that.
But the problem I highlighted was that the top level host_list 
dictionary  didn't exist in your code. You need to initialize
it before you can access the cust key.

host_list = {}
.
.
.
host_list.get(cust, {})

> Then there's a host key with multiple layers:
>
>     host_list['alan']['webserver']['ip'] = '12.23.34.45'
>     host_list['alan']['webserver']['environ'] = 'Dev'
>
> Make sense? As I do not know a lot about classes I'm not sure they are
> better in this case than a multi-level dictionary.

A class is effectively a dictionary inside so its very similar.
Using my OOP suggestion above this would translate to something like:

alan.servers['webserver'].ip = '12.23.34.45

Which you find more readable is a matter of taste!
There are some other advantages to the OOP approach but
they are not critical here.

> The data does not get altered, just organized.

That doesn't make much difference in this case.

The simplest solution to get it working is probably just
to move the customers list into the functions module.
In the longer term the other options might prove more beneficial.

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



More information about the Tutor mailing list