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
  Container “Not defined” PythonGuru 24 1,089 8 hours ago
Last Post: ndc85430
  NameError: name 'u1' is not defined (on parser code Python) Melcu54 1 150 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 396 Jun-14-2021, 03:41 PM
Last Post: deanhystad
Video name is not defined pygauss10 6 365 Jun-10-2021, 05:43 PM
Last Post: pygauss10
  [split] NameError: name 'start_with_first_selected' is not defined knoxvilles_joker 4 600 Apr-18-2021, 07:59 PM
Last Post: knoxvilles_joker
  Error when refering to class defined in 'main' in an imported module HeRo 2 475 Apr-13-2021, 07:22 PM
Last Post: HeRo
Sad Function defined by branches antoniogalante 1 423 Dec-16-2020, 11:35 PM
Last Post: deanhystad
  Why does lambda throw 'name value_o is not defined' error? karabakh 3 549 Dec-14-2020, 05:45 PM
Last Post: karabakh
  “NameError” “is not defined” script that I know works on other computers iamwithstupid 0 585 Nov-24-2020, 04:23 PM
Last Post: iamwithstupid
  NameError: name 'L2' is not defined soshelby 5 995 Nov-05-2020, 08:50 PM
Last Post: soshelby

Forum Jump:

User Panel Messages

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