NameError: name 'FunctionName' is not defined - python

I have two files. One named MainMenu.py another named MissionMenu.py for a simple text game I was making. But I ran into an issue (I'm still rather new to this) that is giving me a NameError:.
The first file looks like this
from MissionMenu import *
def mainMenu():
x = input("Type Something:")
missionMenu()
mainMenu()
The second File looks like this
from MainMenu import *
def missionMenu():
x = input("Type something else:")
mainMenu()
missionMenu()
The error says
NameError: name 'missionMenu' is not defined

look at this: Call a function from another file in Python
You are using import incorrectly. Yo don't need to add .py
from MissionMenu import missionMenu
def mainMenu():
x = input("Type Something:")
missionMenu()
mainMenu()
also, it's a bad idea in each file to import the other. kind of circular loop. Think which file really needs the other one. Probably they don't need to import each other

First of all you do not need a .py.
Suppose, If you have a file a.py and inside you have some functions:
def b():
# Something
return 1
def c():
# Something
return 2
And you want to import them in z.py you have to write
from a import b, c
Source and Details : Call a function from another file in Python

Two issues about your code:
Imports
To import a file called MainMenu.py:
import MainMenu
So do not use .py after that name.
Dependencies
You should keep your dependencies straight:
Do not import MissionMenu from MainMenu that imports MissionMenu
Just keep it simple ^^
Edit:
If you want to have multiple scripts that contain different menus,
just create a function in those scripts (they are called modules then).
Import them in your main application (don't import the main script in the module) and run the function from the main file.
Hope this is helpful ^^

Related

Can I print a variable from one function in another .py file

for example lets say I have a file called "utils.py".
I have a function that passes user input through a series of "if" statements. Every time X conditions are met the original variable is altered and saved as a new variable then passed down to the next if statement.
I want to access the final altered variable from a source file called "main.py". I would prefer if there was a method with no temp file. I have searched for an answer online for a while but found nothing quite as specific as what i am looking for.
to clarify i have a file called "utils"
if x == "y":
s = x.replace("blah", "blah")
print s
global I1_b
I1_b = s
then in another file called "main" i would like to call I1_b
if this == "that":
print(I1_b)
You can import the utils.py file in the main.py file, then use I1_b there.
It would like this:
# In main.py
import utils
if this == "that":
print(utils.I1_b)
The logic in the utile.py folder would be better inside a function and import that function in the main.py file. The code in utils.py will now always be executed once you import anything from it.
from utils import function_x
print(function_x())
global is not the correct tool here. That is used inside a module (file) to define a global scope (https://www.programiz.com/python-programming/global-keyword), and read/edit variables accordingly.
The best solution is to import the I1_b variable from the utils module, like: from utils import I1_b, and use it as you intended
def get_value(x):
if x == "y":
s = x.replace("blah", "nah")
print(f"X is {x}")
return s
your_answer = get_value(input("Input y: "))
print(your_answer)
To access it from another file, see #barmar comment import utils

I'm making the snake game in Python3 and keep getting this Error: name 'Tk' is not defined what should I do? [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 6 months ago.
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
First, import function from file.py:
from file import function
Later, call the function using:
function(a, b)
Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.
Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.
Do not write .py when importing.
Let file_a.py contain some functions inside it:
def f():
return 1
def g():
return 2
To import these functions into file_z.py, do this:
from file_a import f, g
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py, then following way you can do it:
Define import statement in Example3.py - file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
Method 1. Import the specific function(s) you want from file.py:
from file import function
Method 2. Import the entire file:
import file as fl
Then, to call any function inside file.py, use:
fl.function(a, b)
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1
Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2
Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
To fix
ModuleNotFoundError: No module named
try using a dot (.) in front of the filename to do a relative import:
from .file import function
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
import module
module.function_name()
or
import pizza
pizza.pizza_function()
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
from pizza import pizza_function
pizza_function()
or
from pizza import pizza_function as pf
pf()
or
from pizza import *
pizza_function()
First save the file in .py format (for example, my_example.py).
And if that file have functions,
def xyz():
--------
--------
def abc():
--------
--------
In the calling function you just have to type the below lines.
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200
You don't have to add file.py.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Solution1: In one file myfun.py define any function(s).
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
In the other file:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
Solution2: if this above solution did not work for Colab
Create a foldermyfun
Inside this folder create a file __init__.py
Write all your functions in __init__.py
Import your functions from Colab notebook from myfun import *
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py
in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py i have import my function with below syntax
from modules.passwordGen import passGen
Just a quick suggestion,
Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.
Just change the file name from where you want to import by:
right-clicking on the file and clicking on refactor-> rename.
Your auto-import option will start coming up

Heroku Python import local functions

I'm developing a chatbot using heroku and python. I have a file fetchWelcome.py in which I have written a function. I need to import the function from fetchWelcome into my main file.
I wrote from fetchWelcome import fetchWelcome in main file. But because we need to mention all the dependencies in the requirement file, it shows error. I don't know how to mention user defined requirement.
How can I import the function from another file into the main file ? Both the files ( main.py and fetchWelcome.py ) are in the same folder.
You're quite close to the answer to the question. Importing works like this:
fetchWelcome.py:
def foo():
# Do something here
print("Hello World")
def bar():
# Do something else
print("Python")
main.py:
import fetchWelcome
fetchWelcome.foo()
fetchWelcome.bar()
If you only want to import a single function, use
from fetchWelcome import foo
foo()
Both files have to be in the same folder.
If we need to import function from fileName into main.py, write
from .fileName import functionName
Thus we don't need to write any dependency in requirement file.

Calling function from another file, which contains variable declared in main file

I'm creating simple notepad program in Tkinter. I decided to put functions in separate file. Is it possible if the functions are operating on variables declared in main file?
This is snippet of the code:
main.py
from tkinter import *
from otherfile import cut
root = Tk()
....
menu_edit.add_command(label='Cut', compound='left', command=cut)
...
main_text = Text(root, wrap ='word')
main_text.pack(expand='yes', fill = 'both')
now I have otherfile.py
def cut():
main_text.event_generate('<<Cut>>')
return 'break'
Once I run it I'll get:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:...\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\....otherfile.py", line 3, in cut
main_text.event_generate('<<Cut>>')
NameError: name 'main_text' is not defined
So I guess otherfile.py does not understand main_text which is defined in main.py. Is there a way to bypass it and allow me to put all the functions in different py file?
cut is trying to use a global variable from another file. Even if you found a way to get around circular imports, it's a messy way to go about things. It's better to write functions that operate independent of global variables. For one thing, it makes them much easier to modify and test. When you need to deal with assigning command=function and function takes variables, functools.partial is your friend.
def cut(tk_text_obj):
tk_text_obj.event_generate('<<Cut>>')
return 'break'
and then in main file, first declare main_text and then use functools.partial to create a callable that takes no arguments.
from functools import partial
from tkinter import *
from otherfile import cut
root = Tk()
....
main_text = Text(root, wrap ='word')
cut_main_text = partial(cut, main_text)
menu_edit.add_command(label='Cut', compound='left', command=cut_main_text)
# or just combine the above two lines using command=partial(cut, main_text)
...
main_text.pack(expand='yes', fill = 'both')
It is possible. You should import main in otherfile or modify otherfile.cut method to accept main_text as method argument. Second option depends on that if menu_edit.add_command allows passing arguments to command.
I think you have two problems.
Circular imports which are a real pain.
Everything which is declared on module level is called during module import.
I believe below example is moreover situation you have.
a.py:
import b
commands = []
def add_command(cmd):
commands.append(cmd)
def run_commands():
for cmd in commands:
print cmd()
def local_cmd():
return 'local cmd output'
if __name__ == '__main__':
add_command(local_cmd)
add_command(b.b_cmd)
run_commands()
b.py:
import a
def b_cmd():
l = a.local_cmd()
return 'B %s B' % l
Above snippet works as expected when running with python a.py.
But when you skip if __name__ == '__main__': you will observe similar situation. Script fails because when you import a in b, add_command(b.b_cmd) in a is called, but b was not imported yet.
It is a bad practice and tons of headache to use global variables. May I suggest to modify cut() to take a parameter:
# otherfile.py
def cut(text_control):
text_control.event_generate('<<Cut>>')
return 'break'
Then in the main module, call it as such:
# main.py
menu_edit.add_command(label='Cut', compound='left', command=lambda: cut(main_text))
This way, you don't have to deal with troubles later. Besides, you can now use function cut() for other text boxes if you want.

How do I call a function from another .py file? [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 6 months ago.
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
First, import function from file.py:
from file import function
Later, call the function using:
function(a, b)
Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.
Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.
Do not write .py when importing.
Let file_a.py contain some functions inside it:
def f():
return 1
def g():
return 2
To import these functions into file_z.py, do this:
from file_a import f, g
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py, then following way you can do it:
Define import statement in Example3.py - file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
Method 1. Import the specific function(s) you want from file.py:
from file import function
Method 2. Import the entire file:
import file as fl
Then, to call any function inside file.py, use:
fl.function(a, b)
Note: If you are working with Jupiter notebook you may need to change path for method 1. :
os.chdir('/')
see https://stackoverflow.com/a/35665295/1984636
And for method 2:
import sys
sys.path.append('../src/')
see https://stackoverflow.com/a/55623567/1984636
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1
Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2
Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
To fix
ModuleNotFoundError: No module named
try using a dot (.) in front of the filename to do a relative import:
from .file import function
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
import module
module.function_name()
or
import pizza
pizza.pizza_function()
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
from pizza import pizza_function
pizza_function()
or
from pizza import pizza_function as pf
pf()
or
from pizza import *
pizza_function()
First save the file in .py format (for example, my_example.py).
And if that file have functions,
def xyz():
--------
--------
def abc():
--------
--------
In the calling function you just have to type the below lines.
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200
You don't have to add file.py.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Solution1: In one file myfun.py define any function(s).
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
In the other file:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
Solution2: if this above solution did not work for Colab
Create a foldermyfun
Inside this folder create a file __init__.py
Write all your functions in __init__.py
Import your functions from Colab notebook from myfun import *
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py
in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py i have import my function with below syntax
from modules.passwordGen import passGen
Just a quick suggestion,
Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.
Just change the file name from where you want to import by:
right-clicking on the file and clicking on refactor-> rename.
Your auto-import option will start coming up

Categories

Resources