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
  Variable not defined, but it is defined... i think ET_ 1 443 Oct-14-2025, 08:28 PM
Last Post: snippsat
  Regarding Defined Functions Hudjefa 1 1,326 Nov-05-2024, 04:59 AM
Last Post: Gribouillis
  NameError: name 'pi' is not defined katebishop 2 4,112 Jul-15-2024, 05:48 AM
Last Post: Pedroski55
Question Variable not defined even though it is CoderMerv 3 4,555 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  I'm getting a NameError: ...not defined. vonArre 2 12,683 Mar-24-2024, 10:25 PM
Last Post: vonArre
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 2,699 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 11,637 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  'answers 2' is not defined on line 27 0814uu 4 2,679 Sep-02-2023, 11:02 PM
Last Post: 0814uu
  tk is not defined jip31 8 19,900 Aug-03-2023, 05:01 PM
Last Post: tralfazy
  Calling a function (which accesses a library) from another file mouse9095 4 6,268 Jun-07-2023, 08:55 PM
Last Post: deanhystad

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.