-6

I'm tracing a legacy project, and see the source code is doing this:

globals()['my-str']

I know we use global keyword when we want to change the value for the global variable in a local scope.

But what does global() do?

user1187968
  • 7,154
  • 16
  • 81
  • 152
  • 2
    https://docs.python.org/3/library/functions.html#globals and https://stackoverflow.com/questions/30958904/why-is-globals-a-function-in-python – wkl Feb 17 '23 at 20:15
  • 7
    Notice it says `globals`, not `global`. [Please try](https://meta.stackoverflow.com/questions/261592/) to look things up before asking questions, for example by [using a search engine](https://duckduckgo.com/?q=python+globals+function). There is nothing at all "legacy" about this built-in function, which is still provided and not deprecated in current versions of Python. It's just that it solves a problem that is usually better sidestepped entirely. – Karl Knechtel Feb 17 '23 at 20:17
  • 2
    You've inherited bad code – roganjosh Feb 17 '23 at 20:23

1 Answers1

-1

You can use the python interperter or pydoc to help you answer questions about keywords and builtins

$> pydoc globals

output:

Help on built-in function globals in module __builtin__:

globals(...)
    globals() -> dictionary
    
    Return the dictionary containing the current scope's global variables.
(END)

edit: globals is not a keyword, it is a builtin

VoNWooDSoN
  • 1,173
  • 9
  • 13
  • 3
    Note the _Answer Well-Asked Questions_ section of [How to Answer](https://stackoverflow.com/help/how-to-answer), and the references therein both to "questions that have been asked (and answered) many times before", and to https://stackoverflow.com/help/on-topic (which explicitly defines questions caused by a typographic error -- in this case, failing to distinguish `global` vs `globals` -- as off-topic). – Charles Duffy Feb 17 '23 at 20:22
  • 2
    To be clear, `globals` isn't a keyword. – wjandrea Feb 17 '23 at 20:28
  • https://youtu.be/N7v0yvdkIHg – VoNWooDSoN Mar 19 '23 at 00:09