views:

220

answers:

3

I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function;

e.g.

def make_hand(deck, handname):
    handname = []
    for c in range(5):
        handname.append(deck.pop())
    return handname

    # deck being a list containing all the cards in a deck of cards earlier

The issue is that this creates a list called handname when i want it to be called whatever the user enters as handname when creating the hand.

Anyone can help? thanks

+1  A: 

Since you are returning the list I don't see how the name of it within the function matters. Can you provide more context on what you want to do?

Teifion
In this example it doesn't matter much, this function works fine as is, it's just that in later function (titled make_game) I need it to be making several hands with different names and I was just looking for a relatively clean way of doing this.
I would go with the dictionary suggestion from Kiv
Teifion
+6  A: 

You can keep a dictionary where the keys are the name of the hand and the values are the list.

Then you can just say dictionary[handname] to access a particular hand. Along the lines of:

hands = {} # Create a new dictionary to hold the hands.
hands["flush"] = make_hand(deck) # Generate some hands using your function.
hands["straight"] = make_hand(deck) # Generate another hand with a different name.
print hands["flush"] # Access the hand later.
Kiv
good idea, thanks
+1  A: 

While you can create variables with arbitrary names at runtime, using exec (as sykora suggested), or by meddlings with locals, globals or setattr on objects, your question is somewhat moot.

An object (just about anything, from integers to classes with 1000 members) is just a chunk of memory. It does not have a name, it can have arbitrarily many names, and all names are treated equal: they just introduce a reference to some object and prevent it from being collected.

If you want to name items in the sense that a user of your program gives a user-visible name to an object, you should use a dictionary to associated objects with names.

Your approach of user-supplied variable names has several other severe implications: * what if the user supplies the name of an existing variable? * what if the user supplies an invalid name?

You're introducing a leaky abstraction, so unless it is really, really important for the purpose of your program that the user can specify a new variable name, the user should not have to worry about how you store your objects - an not be presented with seemingly strange restrictions.

Torsten Marek