Python Forum
changing variable outside of a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
changing variable outside of a function
#1
Hi,

I have the variable sun_Datetime that was initialized globally outside of 2 user defined functions that I have: 1) get_previous_byday(dayname, start_date=None), 2) date_to_str(day, month, year, sun_dtime).

I tried to access the var sun_Datetime inside date_to_str function and change it.

When sun_Datetime initialized outside of date_to_str function, the variable object id is 54219768. Once within date_to_str function, after calling get_previous_byday function to change the sun_Datetime variable, a new object was created with an different id, 37199768 instead.

I declared sun_Datetime as a global variable, doesn't this allow me to access the original variable, id 54219768 and make changes to it?

import datetime
from datetime import datetime, timedelta
import time

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

def get_previous_byday(dayname, start_date=None):
    if start_date is None:
        start_date = datetime.today()
    day_num = start_date.weekday()
    day_num_target = weekdays.index(dayname)
    days_ago = (7 + day_num - day_num_target) % 7
    if days_ago == 0:
        days_ago = 7
    target_date = start_date - timedelta(days=days_ago)
    return target_date

def date_to_str(day, month, year, sun_dtime):
    global sun_Datetime
    global sun_Day
    global sun_Month
    global sun_Year
    print("INSIDE date_to_str() function BEFORE get_previous_byday() function call")
    print("variable: [value, type, id] -->", "sun_Datetime passed as sun_dtime: ", [sun_dtime, type(sun_dtime), id(sun_dtime)], "\n")
    sun_dtime = get_previous_byday('Sunday', sun_dtime) ## reference line 4
    print("INSIDE date_to_str() function AFTER get_previous_byday() function call")
    print("variable: [value, type, id] -->", "sun_Datetime passed as sun_dtime: ", [sun_dtime, type(sun_dtime), id(sun_dtime)], "\n")
    day = sun_dtime.day ## reference line 5
    month = sun_dtime.month ## reference line 6
    year = sun_dtime.year ## reference line 7
    sun_Day = str(day)
    sun_Year = str(year)
    if len(str(month)) == 1:
   sun_Month = '0' + str(month)
    else:
   sun_Month = str(month)

sun_Datetime = get_previous_byday('Sunday')
sun_Day = str(sun_Datetime.day) ## reference line 1
sun_Month = str(sun_Datetime.month) ## reference line 2
sun_Year = str(sun_Datetime.year) ## reference line 3

print("BEFORE calling date_to_str() function")
print("variable: [value, type, id] -->", "sun_Datetime: ", [sun_Datetime, type(sun_Datetime), id(sun_Datetime)], "\n")
print("These variables were initialized OUTSIDE of date_to_str() function on reference line 1, 2, 3")
print("variable: [value, type, id] -->", "sun_Day: ", [sun_Day, type(sun_Day), id(sun_Day)])
print("variable: [value, type, id] -->", "sun_Month: ", [sun_Month, type(sun_Month), id(sun_Month)])
print("variable: [value, type, id] -->", "sun_Year: ", [sun_Year, type(sun_Year), id(sun_Year)], "\n")


date_to_str(sun_Datetime.day, sun_Datetime.month, sun_Datetime.year, sun_Datetime)

print("Tried to change the following variables INSIDE date_to_str() function on reference line 4,5,6 and 7")
print("AFTER calling date_to_str() function")
print("variable: [value, type, id] -->", "sun_Datetime: ", [sun_Datetime, type(sun_Datetime), id(sun_Datetime)], "\n")
print("variable: [value, type, id] -->", "sun_Day: ", [sun_Day, type(sun_Day), id(sun_Day)])
print("variable: [value, type, id] -->", "sun_Month: ", [sun_Month, type(sun_Month), id(sun_Month)])
print("variable: [value, type, id] -->", "sun_Year: ", [sun_Year, type(sun_Year), id(sun_Year)], "\n")
Output:
BEFORE calling date_to_str() function variable: [value, type, id] --> sun_Datetime:  [datetime.datetime(2017, 1, 1, 18, 22, 0, 862455), <class 'datetime.datetime'>, 54219768]  These variables were initialized OUTSIDE of date_to_str() function on reference line 1, 2, 3 variable: [value, type, id] --> sun_Day:  ['1', <class 'str'>, 37478176] variable: [value, type, id] --> sun_Month:  ['1', <class 'str'>, 37732000] variable: [value, type, id] --> sun_Year:  ['2017', <class 'str'>, 37731968]  INSIDE date_to_str() function BEFORE get_previous_byday() function call variable: [value, type, id] --> sun_Datetime passed as sun_dtime:  [datetime.datetime(2017, 1, 1, 18, 22, 0, 862455), <class 'datetime.datetime'>, 54219768]  INSIDE date_to_str() function AFTER get_previous_byday() function call variable: [value, type, id] --> sun_Datetime passed as sun_dtime:  [datetime.datetime(2016, 12, 25, 18, 22, 0, 862455), <class 'datetime.datetime'>, 37199768]  Tried to change the following variables INSIDE date_to_str() function on reference line 4,5,6 and 7 AFTER calling date_to_str() function variable: [value, type, id] --> sun_Datetime:  [datetime.datetime(2017, 1, 1, 18, 22, 0, 862455), <class 'datetime.datetime'>, 54219768]  variable: [value, type, id] --> sun_Day:  ['25', <class 'str'>, 51992256] variable: [value, type, id] --> sun_Month:  ['12', <class 'str'>, 37731968] variable: [value, type, id] --> sun_Year:  ['2016', <class 'str'>, 37478176] 
Reply
#2
You need to include a 'global' statement at the top of the function where used (not where declared)
like:
def myfunc():
   global sun_Datetime
Reply
#3
(Jan-04-2017, 11:45 PM)Larz60+ Wrote: You need to include a 'global' statement at the top of the function where used (not where declared)
Can we PLEASE stop teaching new programmers to do this.
This person should not be using the global keyword for anything. at. all.
Reply
#4
You should use classes. This whole custom date configuration can be a class. Your function would be the classes methods (get_previous_byday and date_to_str) and your global variables would be the classes attributes (weekdays, sun_Datetime, sun_Day, sun_Month, sun_Year). In that way you wouldnt have to use global all over or pass variables back and forth between functions.
Recommended Tutorials:
Reply
#5
You should make a case and pep to suggest it be removed from the language.
I do agree, and never use it myself, but it is indeed a part of the language
And this user had already decided to go that route
Reply
#6
I dont think it should be removed, but i think 99% of people who use it should be doing it another way.
Recommended Tutorials:
Reply
#7
Larz60+ Wrote:You should make a case and pep to suggest it be removed from the language.
It absolutely should not be removed from the language, but this isn't a good use case for it. This argument is just as valid as asking why I don't write a pep to remove eval/exec. They serve a purpose; this isn't it.

One of the main reasons to use it is to define constants within a function. And after definition to not change them. Say you are programatically building up a large dictionary which you want to be a global constant but don't want any other variables needed in the building process defined globally. Even then you could just return and assign. It is almost never the right thing to do, and in code of new programmers I have NEVER seen a single case where it was.

The fact that the OP had already committed towards doing the wrong thing is even more a reason to try to correct them.

I actually do use the global keyword as can be seen here:
https://github.com/Mekire/pygame-samples...im.py#L217
The use in this situation is some preprocessing on an object that both can't be created until another module is initialized and requires a conversion in order to use efficiently. Not using the global keyword would mean I needed to init the module in the global namespace which I stylistically don't like. It is also defined in caps to indicate it is indeed to be treated as a constant.
Reply
#8
Praise in public, Criticize in private!
Reply
#9
Hi,

thank you everyone for your help and suggestions!

I'll try to rework it using Class and see what I'm going to come up with.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 546 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 514 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,165 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 892 Aug-07-2023, 05:58 PM
Last Post: Karp
  Changing a string value to a numerical value using python code and a lamda function Led_Zeppelin 6 1,539 Jul-05-2022, 11:29 PM
Last Post: deanhystad
  Retrieve variable from function labgoggles 2 999 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Keeping a value the same despite changing the variable it was equated to TheTypicalDoge 2 1,433 Mar-13-2022, 10:50 PM
Last Post: Yoriz
  Cant transfer a variable onto another function KEIKAS 5 1,835 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  Please explain uncommon way of declaring and using variable [function.variable] esphi 4 2,286 Nov-07-2020, 08:59 AM
Last Post: buran
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,157 Sep-18-2020, 02:50 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020