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
  Getting "name 'get_weather' is not defined error and no json_data returned? trthskr4 6 364 Sep-14-2021, 09:55 AM
Last Post: trthskr4
  How to use a function from third party library? rrowhe4d 2 189 Aug-31-2021, 04:30 PM
Last Post: Larz60+
  Override a library function that is not in __all__ Weird 7 651 Aug-23-2021, 05:03 PM
Last Post: Larz60+
  NameError: name 'Particle' is not defined in Pygame drunkenneo 4 356 Aug-15-2021, 06:12 PM
Last Post: bowlofred
  NameError: name 'u1' is not defined (on parser code Python) Melcu54 1 342 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 590 Jun-14-2021, 03:41 PM
Last Post: deanhystad
Video name is not defined pygauss10 6 558 Jun-10-2021, 05:43 PM
Last Post: pygauss10
  [split] NameError: name 'start_with_first_selected' is not defined knoxvilles_joker 4 778 Apr-18-2021, 07:59 PM
Last Post: knoxvilles_joker
  Error when refering to class defined in 'main' in an imported module HeRo 2 604 Apr-13-2021, 07:22 PM
Last Post: HeRo
Sad Function defined by branches antoniogalante 1 500 Dec-16-2020, 11:35 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