Why am I getting a NameError when I try to call my function?

This is my code:

import os

if os.path.exists(r'C:\Genisis_AI'):
    print("Main File path exists! Continuing with startup")
else:
    createDirs()

def createDirs():
    os.makedirs(r'C:\Genisis_AI\memories')

When I execute this, it throws an error:

File "foo.py", line 6, in <module>
    createDirs()
NameError: name 'createDirs' is not defined

I made sure it's not a typo and I didn't misspell the function's name, so why am I getting a NameError?


Solution 1:

You can't call a function unless you've already defined it. Move the def createDirs(): block up to the top of your file, below the imports.

Some languages allow you to use functions before defining them. For example, javascript calls this "hoisting". But Python is not one of those languages.


Note that it's allowable to refer to a function in a line higher than the line that creates the function, as long as chronologically the definition occurs before the usage. For example this would be acceptable:

import os

def doStuff():
    if os.path.exists(r'C:\Genisis_AI'):
        print("Main File path exists! Continuing with startup")
    else:
        createDirs()

def createDirs():
    os.makedirs(r'C:\Genisis_AI\memories')

doStuff()

Even though createDirs() is called on line 7 and it's defined on line 9, this isn't a problem because def createDirs executes before doStuff() does on line 12.