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
  Why built in functions are defined as class? quazirfan 5 402 Oct-23-2021, 01:20 PM
Last Post: Gribouillis
  NameError: name “x” is not defined ... even though x is defined campjaybellson 7 378 Oct-20-2021, 05:39 PM
Last Post: deanhystad
  Exit function from nested function based on user input Turtle 5 330 Oct-10-2021, 12:55 AM
Last Post: Turtle
  name 'x' is not defined dolev28 2 631 Sep-28-2021, 01:57 PM
Last Post: dolev28
  Getting "name 'get_weather' is not defined error and no json_data returned? trthskr4 6 506 Sep-14-2021, 09:55 AM
Last Post: trthskr4
  How to use a function from third party library? rrowhe4d 2 294 Aug-31-2021, 04:30 PM
Last Post: Larz60+
  Override a library function that is not in __all__ Weird 7 838 Aug-23-2021, 05:03 PM
Last Post: Larz60+
  NameError: name 'Particle' is not defined in Pygame drunkenneo 4 487 Aug-15-2021, 06:12 PM
Last Post: bowlofred
  NameError: name 'u1' is not defined (on parser code Python) Melcu54 1 478 Jul-26-2021, 04:36 PM
Last Post: snippsat
  I am getting a NameError that is not defined and not sure why it happen rick0922 5 708 Jun-14-2021, 03:41 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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