When is logging.getLogger(__name__) needed?
Loris Bennett
loris.bennett at fu-berlin.de
Tue Apr 4 07:58:24 EDT 2023
Peter Otten <__peter__ at web.de> writes:
> On 31/03/2023 15:01, Loris Bennett wrote:
[snip (53 lines)]
> Your problem has nothing to do with logging -- it's about visibility
> ("scope") of names:
>
>>>> def use_name():
> print(name)
>
>
>>>> def define_name():
> name = "Loris"
>
>
>>>> use_name()
> Traceback (most recent call last):
> File "<pyshell#56>", line 1, in <module>
> use_name()
> File "<pyshell#52>", line 2, in use_name
> print(name)
> NameError: name 'name' is not defined
>
> Binding (=assigning to) a name inside a function makes it local to that
> function. If you want a global (module-level) name you have to say so:
>
>>>> def define_name():
> global name
> name = "Peter"
>
>
>>>> define_name()
>>>> use_name()
> Peter
Thanks for the example and reminding me about Python's scopes.
With
global name
def use_name():
print(name)
def define_name():
name = "Peter"
define_name()
use_name()
I was initially surprised by the following error:
~/tmp $ python3 global.py
Traceback (most recent call last):
File "/home/loris/tmp/global.py", line 10, in <module>
use_name()
File "/home/loris/tmp/global.py", line 4, in use_name
print(name)
NameError: name 'name' is not defined
but I was misinterpreting
global name
to mean
define a global variable 'name'
whereas it actually seems to mean more like
use the global variable 'name'
Correct?
--
This signature is currently under constuction.
More information about the Python-list
mailing list