1

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
  • I'm not so sure this is a good idea. :) Try using a dictionary instead. Commented Feb 1, 2009 at 16:00

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.