Alexander Craggs
Alexander Craggs

Reputation: 8759

What are the downsides of globals()['var'] in Python?

This post says that you can have a variable variable by using the syntax:

globals()['var']

However, it also says that it's a very bad idea. My question is why? As far as I can see, it is the same as doing:

global var
var

Except, in the first case, it is actually possible to change what the name is. Are there security concerns, or is it simply that it is more difficult to read?

Note - Sorry if this is a duplicate question, doing a search reveals a whole load of questions on global() but I can't see one for this.

Upvotes: 0

Views: 123

Answers (1)

Dr Xorile
Dr Xorile

Reputation: 1009

For short scripts it's not the worst thing in the world. But global variables in general should be avoided, because it makes the code harder to maintain. Normally you pass a variable across to your functions and classes.

An interesting example that sometimes comes up is if you're trying to scipy curve_fit, and you have a function that has many variables, not all of which you want to optimize. One solution would be to make the other variables global, but the generally accepted way is to make a lambda function to separate your two different variables. See here: fitting-only-one-paramter-of-a-function-with-many-parameters-in-python

Upvotes: 1

Related Questions