0

I am using recursive function to get file size in each directory, but getting TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'. However I checked all files inside all subdir, I don't see any file returning None Type:

import os
def disk_usage(path):
    """
    this function resursiverly check file size in each diretory and return size of 
    path/directory
    provided.
    """
    total = os.path.getsize(path)
    if os.path.isdir(path):
        for file in os.listdir(path):
            subdir = os.path.join(path, file)
            print(subdir)
            total +=disk_usage(subdir)
    print ("{} for path {}".format(total, path))
path = "/home/akjha/Documents/Aashutosh_cfengine/"
disk_usage(path)
Stef
  • 13,242
  • 2
  • 17
  • 28
Aashutosh jha
  • 552
  • 6
  • 8
  • Also https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none https://stackoverflow.com/questions/51946790/recursive-function-on-sublist-returning-none https://stackoverflow.com/questions/60261962/recursive-function-return-none – Stef Nov 06 '20 at 15:01
  • In any other language you'd get a warning telling you you forgot a `return` statement, but python likes to pretend everything is alright and silently returns `None` when you forget to explicitly return a value. – Stef Nov 06 '20 at 15:04

2 Answers2

3

At the end of disk_usage you need to add

return total

otherwise without a return statement it will implicitly return None which will cause

total += disk_usage(subdir)

to add an int to None

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

Your method disk_usage() doesn't return anything. In python, a method that doesn't explicitly return something will instead return None by default.

When you recursively call

total +=disk_usage(subdir)

disk_usage(subdir) returns None, which produces your error.

Solution: put

return total

at the end of the function, before de-indenting.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53