Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • Yes I completely agree with you. But when I print locals() before printing that variable it gives empty dict. So where does python look for local variable if not in locals. Commented Oct 5, 2017 at 8:40
  • 1
    It won't look into both. It will look into locals() if the compile step found out that it should be a local variable (using the determinism sketched above). It will look into globals() if the variable was determined at compile time to be a global one. If it doesn't find it there, the exception is thrown. There is no "fallback" to globals() if it isn't found in locals() or vice versa. Commented Oct 5, 2017 at 9:45
  • 1
    All that is true for functions which can have local variables. For classes, you have a different concept; there are no "local" variables but class-global ones (as apposed to module-global ones). In this case, you have the fallback and override mechanism (first class-global variables and subsiding the module-global ones) you wrongly assumed to have at functions with locals and globals. Commented Oct 5, 2017 at 9:48
  • 1
    That information is stored in the produced bytecode. It either will contain code for accessing the local variables on the stack or for accessing the global variables. Which makes it hard to "find out" during runtime (if this is your goal, I'm not sure about your usecase, but it sounds a bit like it this). You could access the variable in a try clase and check the error in case it isn't available. The message probably differs for local and global variables. Commented Oct 6, 2017 at 7:32
  • 1
    I did not accept it because your answer was not what exactly i was looking for. It gets clear from your comments. thats why i vote useful on your comments. docs.python.org/2.7/tutorial/… make it more clear for me. Commented Oct 10, 2017 at 10:42