Python Forum
python library not defined in user defined function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python library not defined in user defined function
#1
Why doesn't this work?

def main():
    import os
    fileName = "text.txt"
    userfunction(fileName)

def userfunction(fileName):
    os.path.exists(fileName)

main()
I get the following error:
Error:
NameError: name 'os' is not defined
Reply
#2
Because the import is local to your main function. Imports should go at the top of the file, as per PEP 8.
Reply
#3
As mentioned above by ndc85430 you need to import your modules before the actual code functions are executed.

import os

def main():
    fileName = "text.txt"
    userfunction(fileName)

def userfunction(fileName):
    os.path.exists(fileName)

main()
"Often stumped... But never defeated."
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 2 51 2 hours ago
Last Post: CoderMerv
  I'm getting a NameError: ...not defined. vonArre 2 153 Mar-24-2024, 10:25 PM
Last Post: vonArre
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 511 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,160 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  'answers 2' is not defined on line 27 0814uu 4 667 Sep-02-2023, 11:02 PM
Last Post: 0814uu
  tk is not defined jip31 8 9,847 Aug-03-2023, 05:01 PM
Last Post: tralfazy
  Calling a function (which accesses a library) from another file mouse9095 4 766 Jun-07-2023, 08:55 PM
Last Post: deanhystad
  Simple Question - ' defined as "a". ?' Ryan012 10 1,490 May-27-2023, 06:03 PM
Last Post: Ryan012
  Badly defined python code? Ken76 2 569 May-25-2023, 11:05 PM
Last Post: DigiGod
  "Name is not defined" when running a class lil_e 6 3,756 Jan-12-2023, 11:57 PM
Last Post: lil_e

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020