0

I have a dataframe defined earlier by this format

vars()['df_zscore_out1']=

I'm trying to access this dataframe inside a function and call this func()

def func():
  print(vars()['df_zscore_out1'])
func()

But got

KeyError: 'df_zscore_out1'

I tried passing it in the argument and it works

def func(df):
  print(df)
func(vars()['df_zscore_out1'])

Can anyone help to explain this? Thanks!

3
  • 1
    From the docs: "Without an argument, vars() acts like locals()." Commented Dec 22, 2020 at 19:21
  • 1
    "I have a dataframe defined earlier by this format vars()['df_zscore_out1']=" don't do this. Just stop dynamically creating variables. The problem is that in the global scope, vars() returns globals(), and in a local scope, it returns locals(). But you shouldn't be using any of these things, it's a bad design Commented Dec 22, 2020 at 19:22
  • Thanks for the advice. To simplify the question I didn't use actually name, which is supposed to be vars()['df_zscore_out%s' %i] and i is updating each loop. So, I created this dynamic variable along with others inside a for loop so that I can have couple of similar df after. Is there any better ways to do so, if not creating variables dynamically using vars()? Commented Dec 22, 2020 at 20:02

2 Answers 2

3

From the docs:

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

Since it isn't a local, it isn't accessible.

Just pass it in as an argument though. If a function needs data, parameters are how that data should be supplied unless you really need a more flexible solution.

Sign up to request clarification or add additional context in comments.

Comments

1

When vars() is called without any arguments, it's equivalent to locals(), which only returns local variables. At the module level, locals() is equivalent to globals().

So, when you call vars() outside of the function, you are essentially calling globals() and getting a list of global variables. When you call vars() inside func(), you are essentially calling locals() and getting the (empty) list of local variables in func().

In order for vars() to be meaningful in this scenario, you'd need to pass the specific object you are trying to store variables in (i.e. a module, class, or instance).

Alternatively, you could call globals() directly instead of vars().

Sources:

2 Comments

The global keyword would be of zero use here.
@Carcigenicate Sorry about that! I honestly have no idea where I saw global being referenced. Edited.

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.