Rocksolid Light

Welcome to RetroBBS

mail  files  register  newsreader  groups  login

Message-ID:  

"Gotcha, you snot-necked weenies!" -- Post Bros. Comics


devel / comp.lang.python / Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

SubjectAuthor
* Re: Variable scope inside and outside functions - global statement being overridJacob Kruger
`- Re: Variable scope inside and outside functionsStefan Ram

1
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

<mailman.40.1709729756.3452.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=29588&group=comp.lang.python#29588

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: jacob.kruger.work@gmail.com (Jacob Kruger)
Newsgroups: comp.lang.python
Subject: Re: Variable scope inside and outside functions - global statement
being overridden by assignation unless preceded by reference
Date: Wed, 6 Mar 2024 14:55:46 +0200
Lines: 236
Message-ID: <mailman.40.1709729756.3452.python-list@python.org>
References: <aff560df-2f57-47d9-ad81-74c21960c21d@gmail.com>
<0ccad7a9-eaba-48e6-b972-d89e5a930c11@DancesWithMice.info>
<db322a1b-2d29-4b67-9d5c-3e8d8737c0f5@gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de SpS/NyXDxCs/NhDv8glKyQ9wpvCfX156zWxv9TlZDmYA==
Cancel-Lock: sha1:CmkDi/Z9diLF6GT6X4Lj4olPMnE= sha256:PI0enLh8ppmws2rfY9gldTJnzInvBEwOtrluw6x5QFI=
Return-Path: <jacob.kruger.work@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=S/8zewrN;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.007
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'def': 0.04; 'variable':
0.05; 'moment,': 0.07; 'child': 0.09; 'datetime': 0.09; 'itself,':
0.09; 'meant': 0.09; 'objects,': 0.09; 'ok,': 0.09; 'parse': 0.09;
'populate': 0.09; 'ultimate': 0.09; 'values.': 0.09; 'steps':
0.11; 'import': 0.15; 'problem.': 0.15; 'behaviour': 0.16;
'confused': 0.16; 'confused,': 0.16; 'directly,': 0.16;
'executed': 0.16; 'functions,': 0.16; 'initiate': 0.16;
'iterable': 0.16; 'manipulating': 0.16; 'not)': 0.16; 'psutil':
0.16; 'purely': 0.16; 'removes': 0.16; 'reproduce': 0.16;
'script.': 0.16; 'should,': 0.16; 'something.': 0.16;
'subject:being': 0.16; 'subject:reference': 0.16; 'timezone':
0.16; 'value?': 0.16; 'values,': 0.16; 'variable,': 0.16;
'variables,': 0.16; 'while,': 0.16; 'wrote:': 0.16; 'problem':
0.16; 'python': 0.16; 'values': 0.17; 'instead': 0.17; 'message-
id:@gmail.com': 0.18; 'figure': 0.19; 'reduce': 0.19; 'to:addr
:python-list': 0.20; 'issue': 0.21; "what's": 0.22; 'version':
0.23; 'code': 0.23; 'skip:p 30': 0.23; 'run': 0.23; 'list,': 0.24;
'anything': 0.25; 'actual': 0.25; 'seems': 0.26; 'interact': 0.26;
'object': 0.26; 'else': 0.27; 'local': 0.27; 'function': 0.27;
'sense': 0.28; 'example,': 0.28; 'asked': 0.29; 'it,': 0.29;
'header:User-Agent:1': 0.30; 'seem': 0.31; 'think': 0.32;
'amounts': 0.32; 'else,': 0.32; 'empty': 0.32; 'python-list':
0.32; 'requests,': 0.32; 'same,': 0.32; 'specified': 0.32;
'words,': 0.32; 'unless': 0.32; 'received:192.168.1': 0.32; 'but':
0.32; 'there': 0.33; 'same': 0.34; 'mean': 0.34; 'header:In-Reply-
To:1': 0.34; 'received:google.com': 0.34; 'trying': 0.35; 'fine':
0.35; 'item': 0.35; 'reflect': 0.35; 'yes,': 0.35; 'following':
0.35; 'from:addr:gmail.com': 0.35; 'also,': 0.36; 'functions':
0.36; 'possibly': 0.36; 'work,': 0.36; 'those': 0.36; 'couple':
0.37; 'missing': 0.37; 'main': 0.37; 'really': 0.37; 'top': 0.65;
'similar': 0.65; 'time.': 0.66; 'now,': 0.67; 'types': 0.67;
'back': 0.67; 'outside': 0.67; 'time,': 0.67; 'that,': 0.67;
'exactly': 0.68; 'items': 0.68; 'matter': 0.68; 'revert': 0.68;
'and,': 0.69; 'following:': 0.69; 'relate': 0.69; 'types,': 0.69;
'within': 0.69; 'carry': 0.71; 'ignore': 0.71; 'content': 0.72;
'global': 0.73; 'little': 0.73; 'relevant': 0.73; 'name,': 0.75;
'skip:f 20': 0.75; '8bit%:100': 0.76; 'successful': 0.78;
'moment': 0.81; 'extra': 0.84; 'bid': 0.84; 'executing': 0.84;
'experiment': 0.84; 'forgotten': 0.84; 'honestly,': 0.84;
'manipulated': 0.84; 'occurring': 0.84; 'referenced': 0.84;
'referral': 0.84; 'scope': 0.84; 'skip:% 30': 0.84; 'subject: \n
': 0.84; '\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0': 0.84; 'skip:d 30':
0.86; 'down,': 0.91; 'retain': 0.91
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20230601; t=1709729754; x=1710334554; darn=python.org;
h=content-transfer-encoding:in-reply-to:from:content-language
:references:to:subject:user-agent:mime-version:date:message-id:from
:to:cc:subject:date:message-id:reply-to;
bh=Ivw//I7gJBN2xR/vgAPl/dKx3j6d7PfWcGsD8OL8yLY=;
b=S/8zewrNDLuuI1arH+VEVa4hp5FjBqSUhMuEE8Q2rhSKUfu5LbIBfFVKLJmvCgXRDR
PClR4bNIo/6u7vRVjuN/jgkdsfwKLqMGqO5hWWM2azKXWRbvYZ+MivbUjiyRi/O0mS2e
2t94BInmOSxqrpP41qibplrQkpcfMsXG1fbny6wmaVhhd5Y1WAtl+lM0chobnW+V8Cl4
TNp+ZdixHyf7pP+tSbW86dm45lhxli48f64cBe/8K6cf9i4ojyKGiv8F9Sd/GBiMP+Lx
x8DlnQIRjjpT/N5wFS94ie90lPxNzVzJksiJuSzXiu/FPzT3vTGwruZfGqttyEHW7sde
E8og==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20230601; t=1709729754; x=1710334554;
h=content-transfer-encoding:in-reply-to:from:content-language
:references:to:subject:user-agent:mime-version:date:message-id
:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to;
bh=Ivw//I7gJBN2xR/vgAPl/dKx3j6d7PfWcGsD8OL8yLY=;
b=e5qajObjHRhzL+41jldtKGNlOX8dmpIAAC4UxhhJSpazXBZksFO5Ff7QmFJNeoRCo0
OUd9+R6UsvPOwBy8KRDrAKHzVmQJEe3wMFt3aKC39eMZRqCRD4+0VeEP/oqhMFvBiN52
2f4Cm0LDSk81/1e0oWYQZbIkmkXZxJnp5FDyM+HRXBSne2NJUfczppVPGgdas4FOHNb+
h4Nf3T7DXIwqcEuAoxvjukkQTHweZYsEPHdSt9s5AYZGEikKj0loWS0SIE36MXv17Ha9
FB6N+oqJAAX5Whk+ZaGJ1F5yiimwL43AzlyWnGfUifPj3WQ36jqED7eVrRiVSZu1Z+8y
8+Xg==
X-Gm-Message-State: AOJu0YzRvh6Q1DlEn4bJt99ARNjrOcvPiSxk4S8Gp2aev0dvTmc15kPk
TX9T/s8/mtGF1shiOC4Knonl2IjQSinFa66LDw6bY33Ruo9gPvdKacfdEDZS
X-Google-Smtp-Source: AGHT+IEmr4+Ccnpteg82Q5b5kx6SAwKnmIdm1Bi3PdK9Jlts0IfxWtpCVjvoK1UE+7rkFvzXwsu/DA==
X-Received: by 2002:a05:6402:1053:b0:564:d715:1d67 with SMTP id
e19-20020a056402105300b00564d7151d67mr10455573edu.17.1709729754276;
Wed, 06 Mar 2024 04:55:54 -0800 (PST)
User-Agent: Mozilla Thunderbird
Content-Language: en-US
In-Reply-To: <0ccad7a9-eaba-48e6-b972-d89e5a930c11@DancesWithMice.info>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <db322a1b-2d29-4b67-9d5c-3e8d8737c0f5@gmail.com>
X-Mailman-Original-References: <aff560df-2f57-47d9-ad81-74c21960c21d@gmail.com>
<0ccad7a9-eaba-48e6-b972-d89e5a930c11@DancesWithMice.info>
 by: Jacob Kruger - Wed, 6 Mar 2024 12:55 UTC

Ok, simpler version - all the code in a simpler test file, and working
with two separate variables to explain exactly what am talking about:

# start code

from datetime import datetime, timezone, timedelta

from copy import copy

# initialise original values

dt_expiry = datetime.strptime("1970-01-01 00:00", "%Y-%m-%d
%H:%M").replace(tzinfo=timezone.utc)

l_test = [1, 2, 3]

def do_it():
    global dt_expiry, l_test # asked python to refer to global
variables for both

    # assign new value immediately

    dt_expiry = datetime.now()+timedelta(minutes=5)
    print(dt_expiry.strftime("%Y-%m-%d %H:%M")) # just to show new
value has been assigned
    # grab copy of list for re-use of items
    l_temp = copy(l_test)
    # following line means l_test will later on retain value in global
scope because it was manipulated inside function instead of just
assigned new value
    l_test.clear()
    # replace original set of values
    for i in l_temp: l_test.append(i)
    # add new item
    l_test.append(99)
# end of do_it function

# end code

If you import the contents of that file into the python interpreter,
dt_expiry will start off as "1970-01-01 00:00", and, if you execute
do_it function, it will print out the new value assigned to the
dt_expiry variable inside that function, but if you then again check the
value of the dt_expiry variable afterwards, it's reverted to the 1970...
value?

If I take out the line that removes values from l_test # l_test.clear()
# before appending new value to it, then it will also not retain it's
new/additional child items after the function exits, and will just
revert back to [1, 2, 3] each and every time.

In other words, with some of the variable/object types, if you use a
function that manipulates the contents of a variable, before then
re-assigning it a new value, it seems like it might then actually
update/manipulate the global variable, but, either just calling purely
content retrieval functions against said objects, or assigning them new
values from scratch seems to then ignore the global scope specified in
the first line inside the function?

Hope this makes more sense

Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."

On 2024/03/05 20:23, dn via Python-list wrote:
> Jacob,
>
> Please reduce the problem to a small code-set which reproduces the
> problem. If we can reproduce same, then that tells us something. At
> the very least, we can experiment without having to expend amounts of
> time in a (likely faulty) bid to reproduce the same environment.
>
> Also, code is the ultimate description!
>
>
> Perhaps start with a small experiment:
>
> - after l_servers is created, print its id()
> - after the global statement, print its id()
> - after the clear/reassignment, print its id()
>
> Is Python always working with the same list?
> Please advise...
>
>
> On 6/03/24 07:13, Jacob Kruger via Python-list wrote:
>> Hi there
>>
>>
>> Working with python 3.11, and, issue that confused me for a little
>> while, trying to figure out what was occurring - unless am completely
>> confused, or missing something - was that, for example, when having
>> pre-defined a variable, and then included it in the global statement
>> inside a function, that function was still referring to a completely
>> local instance, without manipulating outside variable object at all
>> unless I first executed a form of referral to it, before then
>> possibly assigning a new value to it.
>>
>>
>> Now, this does not seem to occur consistently if, for example, I just
>> run bare-bones test code inside the python interpreter, but
>> consistently occurs inside my actual testing script.
>>
>>
>> Basically, in a file with python code in that am using for a form of
>> testing at the moment, at the top of the file, under all the import
>> statements, I initiate the existence of a list variable to make use of
>>
>> later:
>>
>>
>> # code snippet
>>
>> l_servers = []
>>
>> # end of first code snippet
>>
>>
>> Then, lower down, inside a couple of different functions, the first line
>> inside the functions includes the following:
>> # code snippet
>>      global l_servers
>> # end code snippet
>>
>> That should, in theory, mean that if I assign a value to that variable
>> inside one of the functions, it should reflect globally?
>>
>> However, it seems like that, while inside those functions, it can be
>> assigned a new list of values, but if I then return to the scope outside
>>
>> the functions, it has reverted back to being an empty list = []?
>>
>>
>> The issue seems to specifically (or not) occur when I make a call to
>> one function, and, in the steps it's executing in one context, while
>> it's not doing anything to the list directly, it's then making a call
>> to the second function, which is then meant to repopulate the list
>> with a brand new set of values.
>>
>>
>> Now, what almost seems to be occurring, is that while just
>> manipulating the contents of a referenced variable is fine in this
>> context, the moment I try to reassign it, that's where the issue is
>> occurring .
>>
>>
>> Here are relevant excerpts from the file:-
>>
>>
>> # start code
>>
>> # original assignation in main part of file
>>
>> l_servers = []
>>
>>
>> # function wich is initially being executed
>>
>> def interact():
>>      global l_servers
>>      # extra code inbetween choosing what to carry out
>>
>>      # ...
>>
>>      # end of other code
>>
>>      bl_response, o_out = list_servers()
>>
>>      if bl_response: # just make sure other function call was successful
>>
>>          l_servers.clear() # first make reference to global variable
>>
>>          for srv in o_out: l_servers.append(srv) # now re-populate items
>>
>>      # end code snippet from inside interact function
>>
>> # end of interact function
>>
>> # end of code snippet
>>
>>
>> That other function being called from within, list_servers() was
>> initially just trying to populate the values inside the global list
>> variable itself, but was ending up in a similar fashion - reverting
>> to initial empty value, but, the above now seems to work, as long as
>> I first make reference to/manipulate/work with global variable
>> instead of just trying to reassign it a brand new value/set of items?
>>
>>
>> So, am I missing something obvious, have I forgotten about something
>> else - yes, know that if was working from within an embedded
>> function, I might need/want to then use the nonlocal statement
>> against that variable name, but, honestly, just not sure how this can
>> be occurring, and, it's not just with this one list variable, etc.?
>>
>>
>> If I try simple test code from within the python interpreter, using
>> different types of variables, this does also not seem to be the same
>> all the time, but, don't think it can relate to an iterable like a
>> list, or else, just in case, here is the code snippet with all the
>> import statements from the top of that file, in case something could
>> be overriding standard behaviour - not likely in this context, but,
>> really not sure what's occurring:
>>
>> # import code snippet
>>
>> import requests, time
>> from requests.auth import HTTPBasicAuth
>> import psutil as psu
>> import pytz
>> import bcrypt
>> from copy import copy
>> from datetime import datetime, timedelta, timezone
>> from dateutil.parser import parse
>>
>> # end of import snippet
>>
>>
>> Thanks if you have any ideas/thoughts on the matter
>>
>>
>> Jacob Kruger
>> +2782 413 4791
>> "Resistance is futile!...Acceptance is versatile..."
>>
>>
>

Re: Variable scope inside and outside functions

<global-20240306141536@ram.dialup.fu-berlin.de>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=29590&group=comp.lang.python#29590

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: Variable scope inside and outside functions
Date: 6 Mar 2024 13:17:45 GMT
Organization: Stefan Ram
Lines: 8
Expires: 1 Feb 2025 11:59:58 GMT
Message-ID: <global-20240306141536@ram.dialup.fu-berlin.de>
References: <aff560df-2f57-47d9-ad81-74c21960c21d@gmail.com> <0ccad7a9-eaba-48e6-b972-d89e5a930c11@DancesWithMice.info> <mailman.40.1709729756.3452.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de vHl/J5uTf6Ig9AuS3MzXEQptCL0eMUJUz27DTeH8EbQBU/
Cancel-Lock: sha1:/IbLrubjJg3gWl9E7LNhltACbb4= sha256:oZkBL/HgTSYIIHM8l6kHRLjNvJ3I1UwntYifAVkccqg=
X-Copyright: (C) Copyright 2024 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE-1901, en-US, it, fr-FR
 by: Stefan Ram - Wed, 6 Mar 2024 13:17 UTC

Jacob Kruger <jacob.kruger.work@gmail.com> writes: if you execute
>do_it function, it will print out the new value assigned to the
>dt_expiry variable inside that function, but if you then again check the
>value of the dt_expiry variable afterwards, it's reverted to the 1970...
>value?

I can only guess that after "do_it" you might have inadvertently
restarted the interpreter.

1
server_pubkey.txt

rocksolid light 0.9.8
clearnet tor