Related
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
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 ^^
I'm bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.
What I did was define them in my projects main.py file, as following:
# ../myproject/main.py
# Define global myList
global myList
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
I'm trying to use myList in subfile.py, as following
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
globals()["myList"].append("hey")
An other way I tried, but didn't work either
# ../myproject/main.py
# Import globfile
import globfile
# Save myList into globfile
globfile.myList = []
# Import subfile
import subfile
# Do something
subfile.stuff()
print(globfile.myList[0])
And inside subfile.py I had this:
# ../myproject/subfile.py
# Import globfile
import globfile
# Save "hey" into myList
def stuff():
globfile.myList.append("hey")
But again, it didn't work. How should I implement this? I understand that it cannot work like that, when the two files don't really know each other (well subfile doesn't know main), but I can't think of how to do it, without using io writing or pickle, which I don't want to do.
The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile does not call init()— that task belongs to main.py:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
See Python's document on sharing global variables across modules:
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
config.py:
x = 0 # Default value of the 'x' configuration setting
Import the config module in all modules of your application; the module then becomes available as a global name.
main.py:
import config
print (config.x)
In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.
You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.
A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.
So, in your example:
# ../myproject/main.py
# Define global myList
# global myList - there is no "global" declaration at module level. Just inside
# function and methods
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
And:
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
# You have to make the module main available for the
# code here.
# Placing the import inside the function body will
# usually avoid import cycles -
# unless you happen to call this function from
# either main or subfile's body (i.e. not from inside a function or method)
import main
main.mylist.append("hey")
Using from your_file import * should fix your problems. It defines everything so that it is globally available (with the exception of local variables in the imports of course).
for example:
##test.py:
from pytest import *
print hello_world
and:
##pytest.py
hello_world="hello world!"
Hai Vu answer works great, just one comment:
In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:
# settings.py
def init(arg):
global myList
myList = []
mylist.append(arg)
# subfile.py
import settings
def print():
settings.myList[0]
# main.py
import settings
settings.init("1st") # global init before used in other imported modules
# Or else they will be undefined
import subfile
subfile.print() # global usage
Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:
# ../myproject/main.py
# Import globfile
import globfile
# Save myList into globfile
globfile.myList = []
# Import subfile
import subfile
# Do something
subfile.stuff()
print(globfile.myList[0])
See the last line? myList is an attr of globfile, not subfile. This will work as you want.
Mike
I just came across this post and thought of posting my solution, just in case of anyone being in the same situation as me, where there are quite some files in the developed program, and you don't have the time to think through the whole import sequence of your modules (if you didn't think of that properly right from the start, such as I did).
In such cases, in the script where you initiate your global(s), simply code a class which says like:
class My_Globals:
def __init__(self):
self.global1 = "initial_value_1"
self.global2 = "initial_value_2"
...
and then use, instead of the line in the script where you initiated your globals, instead of
global1 = "initial_value_1"
use
globals = My_Globals()
I was then able to retrieve / change the values of any of these globals via
globals.desired_global
in any script, and these changes were automatically also applied to all the other scripts using them. All worked now, by using the exact same import statements which previously failed, due to the problems mentioned in this post / discussion here. I simply thought of global object's properties being changing dynamically without the need of considering / changing any import logic, in comparison to simple importing of global variables, and that definitely was the quickest and easiest (for later access) approach to solve this kind of problem for me.
Based on above answers and links within I created a new module called global_variables.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#
# global_variables.py - Global variables shared by all modules.
#
# ==============================================================================
USER = None # User ID, Name, GUID varies by platform
def init():
""" This should only be called once by the main module
Child modules will inherit values. For example if they contain
import global_variables as g
Later on they can reference 'g.USER' to get the user ID.
"""
global USER
import getpass
USER = getpass.getuser()
# End of global_variables.py
Then in my main module I use this:
import global_variables as g
g.init()
In another child imported module I can use:
import global_variables as g
# hundreds of lines later....
print(g.USER)
I've only spent a few minutes testing in two different python multiple-module programs but so far it's working perfectly.
Namespace nightmares arise when you do from config import mySharedThing. That can't be stressed enough.
It's OK to use from in other places.
You can even have a config module that's totally empty.
# my_config.py
pass
# my_other_module.py
import my_config
def doSomething():
print(my_config.mySharedThing.message)
# main.py
from dataclasses import dataclass
from my_other_module import doSomething
import my_config
#dataclass
class Thing:
message: str
my_config.mySharedThing = Thing('Hey everybody!')
doSomething()
result:
$ python3 main.py
Hey everybody!
But using objects you pulled in with from will take you down a path of frustration.
# my_other_module.py
from my_config import mySharedThing
def doSomething():
print(mySharedThing.message)
result:
$ python3 main.py
ImportError: cannot import name 'mySharedThing' from 'my_config' (my_config.py)
And maybe you'll try to fix it like this:
# my_config.py
mySharedThing = None
result:
$ python3 main.py
AttributeError: 'NoneType' object has no attribute 'message'
And then maybe you'll find this page and try to solve it by adding an init() method.
But the whole problem is the from.
I have 2 python files. file1.py and file2.py
file1.py
print "file1"
file2.py
import file1
print "file2"
and when i run file2,the output is
file1
file2
The question may seem little naive but i want to know what exactly is happening here.
Thanks in Advance.
Yes.
When importing a file it is being run.
To avoid this, file1.py can be:
if __name__=='__main__':
print 'file1'
And then the text will be printed only if file1.py is the main file being run directly.
In a sense yes. When you import a file, you will run all the script and you will also initialize all the methods.
To ensure that code is only run when the file is run directly and not when it is imported. You should put all your main code in main() and do it as:
def main():
#all your main code here
if __name__ == '__main__':
main()
The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the import statement is defined as a call to the import() function, with the appropriate arguments. The return value of import() is used to perform the name binding operation of the import statement. See the import statement for the exact details of that name binding operation.
import file using python
To print 'file2' your code, you need to pass it as a command to the Python interpreter,
python myscript.py
there's no main() function that gets run automatically, so the main() function is implicitly all the code at the top level, and call if __name__ == "__main__"
How main does in python
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