Newbie help- Can multiple instances with multiple names automatically created.

Steven D'Aprano steven at
Tue Jan 5 04:52:02 CET 2010

On Mon, 04 Jan 2010 19:12:53 -0800, Nav wrote:

> Okay, let me ask another question:
> When we create instances of objects by doing 
> x = className()
> are we using globalnamespace?

That depends on whether you are doing x = className() inside a function 
(or class), or in the top level of the program.

If I do this:

x = 1234

def function():
    y = 4567

then x is defined in the global namespace and y is defined in the 
namespace which is local to function().

> if yes then:
>   if using globalnamespace is bad then why does every book or tutorial
> about python classes give the above  style of assignment as an example?

No, you're confused -- the problem isn't with using the global namespace. 
The problem is that you don't know what names you want to use ahead of 

You use assignment like:

x = something()

when you know the name x when you are writing the code. That way you can 
write x in the code, and all is good:

x = something()
print x.method()
mydict = {x: -1}
assert mydict.keys() == [x]

Now, imagine that you didn't know what names you have to use. Say, for 
example, that you need a variable number of Somethings:

a = Something()
b = Something()
c = Something()
d = Something()  
# I never know when to stop...
z = Something()
# ... keep going? too far? who knows??? HELP!
# when do I stop???
process(y)  # ...

That's the wrong way to deal with it. So instead you use a list:

mylist = []  # define ONE NAME in the global namespace
for i in range(some_number):
# later...
for x in mylist:  # again, we use ONE name, `x`

A list implicitly maps numbers (the position) to values. If you want to 
map strings (names) to values, use a dict. Here is an example. Notice we 
don't know how many players there are, or what their names are:

print "Welcome to the game."
print "Please enter the name of each player,"
print "or the word 'STOP' when there are no more players."
players = {}
i = 1
while True:
    # loop forever
    name = raw_input("Name of player %d? " % i)
    name = name.strip()  # get rid of extra whitespace
    if name.upper() == 'STOP':
        # we're done
    players[name] = NewPlayer()

# much later...
for name, player in players.items():
    print "Welcome, player %s" % name

The only downside is that dicts are unordered, so the order of the 
players is not the same as the order they were entered in.


More information about the Python-list mailing list