Replies: 6 comments
-
Try this one: |
Beta Was this translation helpful? Give feedback.
-
Apologies for the delayed response. Would you happen to know where I can find more information about this command and what other things it could affect? |
Beta Was this translation helpful? Give feedback.
-
As a preface/warning, using global variables like this is generally discouraged for a variety of reasons. You can find many articles discussing why this is the case with a cursory web search, so I won't expand on this here. Generally, when you can't access an outer variable inside an inner scope in python, it's because you assign to the variable somewhere in the inner scope. If you set a variable's value in an inner scope, python masks the variable from the outer scope, preventing you from accidentally overwriting its global value. Usually this is the behavior you want, but it can be confusing if you are trying to achieve something different. To get around this, usually all you need to do is add a @router.get("/", status_code=200)
async def get_items(username):
global GLOBAL_CONFIG # <-- like this
# username is a query parameter
# domain.com/api/items?username=mrvaghani
if username not in GLOBAL_CONFIG["username"]:
return JSONResponse(
status_code=404,
content={"message": "Not Found"}) (Note that in some cases the It doesn't look like you are doing anything here that would cause the If not, a traceback might help. |
Beta Was this translation helpful? Give feedback.
-
I completely agree with the global config's being a bad idea. I just needed something quick to get my config into the application and this was the only way to deal with it in my environment. I do have plans to move to ENV files at some point in future. I have modified my original Appreciate the feedback! :) |
Beta Was this translation helpful? Give feedback.
-
Closing for now as I am no longer able to recreate this issue. Will re-open if needed. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here everyone! Thanks @mrvaghani for reporting back and closing the issue 👍 |
Beta Was this translation helpful? Give feedback.
-
First check
Description
How can I import and use a global variable defined inside another python file?
In my testing so far, I am able to access the value of that variable right before the function. But if I access it inside the function decorated with
@router.get
, I get an error for variable not defined.A response to another question about global variables say that this should work. What am I doing wrong?
Additional context
This causes the variable GLOBAL_CONFIG to be undefined when called inside the function but has the right value for the
print
statement right before the function.Please let me know if there is any additional information or troubleshooting I can perform to help provide more information on this issue.
Beta Was this translation helpful? Give feedback.
All reactions