0

I would like to use a function's parameter to create dynamic names of dataframes and/or objects in Python. I have about 40 different names so it would be really elegant to do this in a function. Is there a way to do this or do I need to do this via 'dict'? I read that 'exec' is dangerous (not that I could get this to work). SAS has this feature for their macros which is where I am coming from. Here is an example of what I am trying to do (using '@' for illustrative purposes):

def TrainModels (mtype):
    model_@mtype = ExtraTreesClassifier()
    [email protected](X_@mtype, Y_@mtype)
TrainModels ('FirstModel')
TrainModels ('SecondModel')

2 Answers 2

1

You could use a dictionary for this:

models = {}

def TrainModels (mtype):
    models[mtype] = ExtraTreesClassifier()
    models[mtype].fit()
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, any name you define within your TrainModels function will be local to that function, so won't be accessible in the rest of your program. So you have to define a global name.

Everything in Python is a dictionary, including the global namespace. You can define a new global name dynamically as follows:

my_name = 'foo'
globals()[my_name] = 'bar'

This is terrible and you should never do it. It adds too much indirection to your code. When someone else (or yourself in 3 months when the code is no longer fresh in your mind) reads the code and see 'foo' used elsewhere, they'll have a hard time figuring out where it came from. Code analysis tools will not be able to help you.

I would use a dict as Milkboat suggested.

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.