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

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.

Leave a Comment