0

Scenario: I declared a variable with value 0 in the method; Then I passed this variable as a parameter to another method which is called from first method. Nested method incremented value of the parameter However, the value of the variable remained to be 0

Question: how to update value of the declared variable

Example:

def doSomething(parameter):
  number = 0
  doIncrement(parameter, number)
  print(f'New number is: {number}') // New number is: 0

def doIncrement(param, counter):
  for item in param.items(param):
    if not isCountable(item):
      # do something
    else:
      counter += 1
      print('number in the counter:', counter) // number in the counter: 1

I understand there is no reference that points on counter, so may be should be something similar to C where we using pointer. How is it done in python?

  • 2
    Python has no pass-by-reference semantics. You can pass a mutable object and update it in the function, but I'd much rather change the code structure that it's not needed, for example, return the counter from `doIncrement`. – bereal Jan 23 '23 at 12:11
  • 1
    You could also consider to have a [global variable](https://peps.python.org/pep-0008/#global-variable-names) and use the [`global`](https://www.w3schools.com/python/gloss_python_global_variables.asp) keyword to modify it – CcmU Jan 23 '23 at 12:29
  • I see, it makes sense now. I used reassignment approach which is working ok. – Andrej Lavrinovic Jan 23 '23 at 12:32
  • 2
    @CcmU: This is **not** a correct use case for global variables, because some other ways (returning the modified value for example) would be more pythonic here. – Serge Ballesta Jan 23 '23 at 12:40
  • @SergeBallesta I do understand that and I strongly agree with you, I just want to clarify that it was another way to have the wanted behavior – CcmU Jan 23 '23 at 19:19

2 Answers2

0

It works now when I reassigned my counter variable with each call like that:

def cleanDir(path):
    print("Start cleaning...")
    removedFiles = 0
    removedFiles = removeFiles(path, removedFiles)
    print(f'Files deleted: {removedFiles}') // prints actual number of delete files

def removeFiles(path, filesCounter):
    for name in os.listdir(path):
        file = path + "\\" + name
        if not os.path.isfile(file):
            filesCounter = removeFiles(file, filesCounter)
            os.rmdir(file)
        else:
            print('Deleting file:', file)
            os.remove(file)
            filesCounter += 1
    return filesCounter
  • 1
    In this case, there's no reason for `filesCounter` to be passed as a parameter to `removeFiles`. `removeFiles` could simply start counting from 0 and return the number of files removed. If you need to add up multiple counts, do it within the calling function. – Stuart Jan 23 '23 at 12:57
  • yes, it does make sense @Stuart . values can be returned by `removeFiles` method. and assigned to the variables in the `cleanDir`. And yes, multiple counters - was a reason why I wanted to pass them as parameters. I didn't know that python supports multiple returns. Awesome. Thank you. – Andrej Lavrinovic Jan 24 '23 at 13:41
0

this is one approach:

def isCountable(item):
    return False

parameter = {1:"hi", 2: 'how ', 3: 'are you'}

def doSomething(parameter):
    number = 0
    number = doIncrement(parameter, number)
    print(f'New number is: {number}') # New number is: 0

def doIncrement(param, counter):
    for item in param.items():
        if not isCountable(item):
            # do something
            ...
    else:
        counter += 1
        print('number in the counter:', counter)  # number in the counter: 1
    return counter

doSomething(parameter)
tierriminator
  • 587
  • 5
  • 19
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 24 '23 at 20:05