Python function from imported file shows as undefined - python

I have a moveslist.py file with function movesSelection and a main.py file. Within my main.py, I've made sure that my variables are set to global and I had another function makeNewChar. Within makeNewChar, I'm trying to call movesSelection but I get "NameError: name 'movesSelection' is not defined.
Since my moveslist.py uses some global variables from main, I imported main into the file.
For my main.py, I did from moveslist import *. I also tried import movesList and from moveslist import movesSelection. All of those threw back errors.
How can I use movesSelection within my main.py?

There may be a few different reasons but some of the most common are having a file with the same name or likely the file you are looking for is in another directory so i will show you my correct here
[Edit] You should remove the .py when importing example below
## This is "main.py" keep that in mind when viewing
## Change line 4 to import and the python file as Func = Func.py in this context
import Func
Func.Activate()
## This is "Func.py"
class Activate:(
print("Hello World!")
)
Or you may need to do as says below!
##Include file extension and move the file with the folder in the correct space and i'd appreciate it if you'd be so kind to mark this question as correct
import movesSelection.py

Add "from moveslist import movesSelection" into makeNewChar.
You do not have to add the .py suffix when you import.

Related

How can I put functions in different files, but get them all with just one import?

Instead of creating a module.py (containing all the functions), can I create a folder MODULE and collect all the functions in different files?
I'd like to do that in a way that main.py contains import MODULE and, if it's possible, to call the functions directly (fun_1(), fun_2()) without the nomenclature MODULE.fun_1(), MODULE.fun_2(), etc.
I think the only right way is creating __init__.py (import all functions contained in other files) in your MODULE folder. And use statement from MODULE import *. If you wanna use import MODULE and call func in other files then, that never work. Interpreter will raise the NameError, cause there are no the variables.
__init__.py file like this:
from file1 import func_1
from file2 import func_2
Yes.
Create your main file, main.py along with another file where you want to put another function. I will use the other.py file.
In main.py, write
from other import *
Note the missing .py, Python handles that for you.
In other.py, write
def your_function():
return -1
You can have as many functions in here as you want. Now, you can call your_function() in main.py.
Example Repl.it: https://repl.it/repls/MeaslyBurdensomeDesigners

Accessing variable from file pyspark

I have one variable.list file. All variables are defined here, like:
Tablename="emp"
Dbname="hr"
Now I want access all these variables from main.py script.
I have seen some thread on this where it is suggested to do following.
From variable.list import *
But it is throwing error that variable.list not defined.
No module name variable.list
Where to keep variable.list file? How to import all the variables?
When you write import variables.list python searching for variables module not a file. You can rename your file as variables.py then try
import variables

Why is this python code running twice [duplicate]

This question already has an answer here:
Why Python print my output two times when I import the same file in which I am printing?
(1 answer)
Closed 2 years ago.
Here is the code
import random
print("Hello", end="")
print("twice")
and a screenshot of the code
When I execute this code it for some reason is running twice. The problem seems to be from the import random statement, because if I either remove that statement or import some other module it works fine.
What could be the reason for this, should I reinstall Python on my system.
There's nothing wrong with python.
The reason is simple:
Your module is importing itself (because it is also named random) - this has to do with the lookup mechanics of python. python will try to import from your root folder first, before modules from pythonpath are imported.
From the docs:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
The directory containing the input script (or the current directory
when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default.
Since your file (module) is called random.py, import random will import this very file.
Now, what does "import" mean?
The statement import something will cause Python to lookup the name something, starting with the current directory.
Therefore, import random will result in an import of this very file, since its name will shadow the build-in random.
Besides, if the name to import is already in the namespace, then the import statement is ignored.
Once the module to import has been located, its code is executed.
As a result, the flow of your script is as follow:
Lookup the random.py name
Add random to the namespace
Execute the code contained in random.py
The random name already exists in the namespace, so the import random statement is ignored
Print the text
Print the text
The reason for this is you've named the script random.py and inside it you import random.
random will not import the built-in random module but, rather, the random module you've created. This leads to the script executing the same statements twice (and also leads to other ugly errors if you tried and import something from random, like from random import randrange.)
Renaming the script leads to normal behavior.
Because your scripts is called random.py, so when you import random you are executing your script as well. Mind to name correctly your scripts.
your python script is named random.py so when you import random it import itself , in python when you import module it will run it.
therefor you get print twice.
rename your script or remove the import

Python - How to allow the use of a function in different modules?

I have 2 scripts.
Main.py
Update.py
I have a function in Main.py which basically does the following:
def log(message):
print(message)
os.system("echo " + message + " >> /logfile.txt")
And in the Update.py file I have a single function which basically does the update. However throughout the update function, it calls "log(message)" with whatever the message is at that point.
The problem now though is I'm getting a NameError: global name "log" is not defined whenever I try use the function outside of the Main.py script.
Any help? on how I would be able to use the function 'log' wherever?
*Code simplified for explanation.
EDIT:
Main.py imports Update from /Scripts/Update.py
Update.py imports log from Main.py
When i try this, it fails saying "cannot import name Update"
Don't import log from Main. That'll rerun the code in Main.py, since running Main.py as a script and importing it as a module aren't equivalent. Other modules should not depend on functions defined in the main script. Instead, put your log function in another module and import that, or have Main.py explicitly pass a logger to the other modules somehow.
Update: You can't import Update because Python can't find it. Python checks in 4 places for modules to import, but the ones you should be interested in are
the directory the script was from, and
the directories specified in the PYTHONPATH environment variable.
You'll either need to put Main.py and the things it imports in the same directory, or add /Scripts to your PYTHONPATH.
Just add in Update.py the line
from Main import log
and you will be able to call log() from Update.py.
You should import the function:
from Main import log
Or best:
import Main
Main.log()
For modules importing each other, refer How can I have modules that mutually import each other.

Linking Python Files Assistance

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.

Categories