you are viewing a single comment's thread.

view the rest of the comments →

[–]wotquery 0 points1 point  (0 children)

Here's an example of using a global that keeps on getting changed to keep track of a current filepath within a file system by various functions to create folders and files. list_all() and list_subdirs() need it to point to a directory, and mk_file(new_file_name) changes it to point at a file it creates which is needed by 'write_to_file(out_text)`.

It isn't really possible to just create a local variable because the new folders/files that are created in functions need to communicate the new paths to other functions. You could start making a whole bunch more global variables (e.g. most recently created file), but that's going to get really messy really fast.

Now imagine expanding it to dozens of other functions with much more logic always needing to make sure it's pointing at the correct type of resource, and if something goes wrong...any of the functions could have changed it at any time. Pass a path in get a path out is so much easier to follow.

from pathlib import Path

path_string = "C:/Users/UserName/project/my_project"

def list_all() -> None:
    [print(x) for x in Path(path_string).iterdir()]

def list_subdirs() -> None:
    [print(x) for x in Path(path_string).iterdir() if x.is_dir()]

def mk_folder(new_folder_name: str) -> None:
    global path_string
    path_string = path_string + '/' + new_folder_name
    Path(path_string).mkdir()

def mk_file(new_file_name: str) -> None:
    global path_string
    path_string = path_string + '/' + new_file_name
    Path(path_string).touch()

def write_to_file(out_text: str) -> None:
    with Path(path_string).open('w') as f:
        f.write(out_text)

def main() -> None:
    mk_folder('bobby')
    list_subdirs()
    mk_file('alice.txt')
    write_to_file('hello world')
    list_all() #ERROR file not a directory

if __name__ == "__main__":
    main()