I created two files in python
First one is
mym.py
def hello():
print("Hello everyone")
return
def summ(x,y):
total=x+y
return total
and next one is
abc.py
import mym
hello()
x=summ(3,4)
print(x)
And the error msg which I am getting is...both the files are in same working directory and there is no error of module not found...its giving error of function not defined.
Traceback (most recent call last):
File "C:/Users/Nisha/AppData/Local/Programs/Python/Python39/abc.py", line 3, in <module>
hello()
NameError: name 'hello' is not defined
Traceback (most recent call last):
File "C:/Users/Nisha/AppData/Local/Programs/Python/Python39/abc.py", line 3, in <module>
x=summ(3,4)
NameError: name 'summ' is not defined
What is the problem in function definition I am unable to trace...
The abc.py needs to be changed to:
from mym import *
hello()
x=summ(3,4)
print(x)
Otherwise you cannot access the functions.
You can try like this:
import mym
mym.hello()
x = mym.summ(3,4)
print(x)
Related
I've a python call from a powershell terminal.
minimalistic example:
Try {
& python "test.py"
}
Catch {
# Place individual error handling here
$ErrorMessage = "$($_.Exception.Message)"
}
echo $ErrorMessage
test.py raises an error, example content can be:
def make_sum():
return a+b
if __name__ == "__main__":
make_sum()
Why does the $ErrorMessage variable contain only the first line of python traceback?
Traceback (most recent call last):
I'd need complete call stack info as python provides:
Traceback (most recent call last):
File "d:/.../test.py", line 10, in <module>
make_sum()
File "d:/.../test.py", line 7, in make_sum
return a+b
NameError: name 'a' is not defined
Any advice how to get a complete traceback into the string variable in powershell?
Thank you,
Honza
Note: I have reduced my problem so the code is only a few lines (compared to 600)
I have a problem: from main.py I want to import file slave.py. slave.py references a function from main.py, and of course I get a NameError: name 'funcFromMain' is not defined
Here is my code for main.py:
import slave
def funcFromMain():
return 6
print(slave.funcFromSlave())
And here is my code for slave.py:
def funcFromSlave():
one = funcFromMain() # <- this doesn't work
two = 2
return (one + two)
I am getting exact error: (note that both files are in exactly the same directory)
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(slave.funcFromSlave())
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 2, in funcFromSlave
one = funcFromMain()
NameError: name 'funcFromMain' is not defined
I tried adding import main at the top of slave.py, and got the following error:
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 1, in <module>
import slave
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 1, in <module>
import main
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(slave.funcFromSlave())
AttributeError: module 'slave' has no attribute 'funcFromSlave'
With from slave import funcFromSlave instead at the top of main:
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(funcFromSlave())
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 2, in funcFromSlave
one = funcFromMain()
NameError: name 'funcFromMain' is not defined
First you can't import a python module like this :
import slave.py
It must be
from slave import funcFromSlave # to get the funcFromSlave function from slave script
And you need to make sure that the slave.py is in the same directory of main.py or
you need to precise the subdirectory where slave.py exists
And for the later error, its best if you avoid circular imports, cause it will create problems, best to do is to send the value of funcFromMain() to funcFromSlave
main.py :
from slave import funcFromSlave
def funcFromMain():
return 6
print(funcFromSlave(funcFromMain()))
slave.py :
def funcFromSlave(funcFromMain):
one = funcFromMain
two = 2
return (one + two)
output when running main.py :
8
This question already has answers here:
How to mark a global as deprecated in Python?
(4 answers)
Closed 4 years ago.
I have written a package where a sub-module contains a module-level variable deprecated_var that I want to remove, because it was a horrible mistake.
mypkg
- mymodule
- __init__.py
But instead of just leaving my end users with a generic ImportError, I want to print a message that says their import is deprecated, and what they should do. So instead of:
>>> from mypkg.mymodule import deprecated_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'deprecated_var'
I want users to see something like this:
>>> from mypkg.mymodule import deprecated_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: mypkg.mymodule.deprecated_var was removed. Replace
with "from foo.bar import Baz; deprecated_var = Baz()"
How can I achieve that?
I don't think this is possible before python 3.7.
However, in python 3.7 or later, this can be achieved by using the module level __getattr__ added in PEP562.
You'd use like so:
#_deprecated_vars is a dict of keys -> alternatives (or None)
_deprecated_vars: Dict[str, Optional[str]] = {
'deprecated_var': 'from foo.bar import Baz; deprecated_var = Baz()',
'other_deprecated_var': None
}
def __getattr__(name):
if name in _deprecated_vars:
alt_text = '{name} was removed from module {__name__}'
replace_text = _deprecated_vars[name]
if replace_text is not None:
alt_text += f'. Replace with {replace_text!r}.'
raise AttributeError(alt_text)
raise AttributeError(f"module {__name__} has no attribute {name}")
However, I'm not sure this works for your use case of from a.b import deprecated_var. This is more for import a.b; a.b.deprecated_var. See the other answer for the former.
For your specific example, you could use the following:
mymodule/__init__.py:
#deprecated_var = 5
replacement_var = 6
mymodule/deprecated_var.py:
raise ImportError("deprecated_var is deprecated. Use mypkg.mymodule.replacement_var instead")
While this raises the custom ImportError when importing the variable directly:
>>> from mymodule import deprecated_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../mymodule/deprecated_var.py", line 1, in <module>
raise ImportError("deprecated_var is deprecated. Use mypkg.mymodule.replacement_var instead")
ImportError: deprecated_var is deprecated. Use mypkg.mymodule.replacement_var instead
it does nothing when accessing it as a module attribute. Or rather, it throws an AttributeError instead of a deprecation warning:
>>> import mymodule
>>> mymodule.deprecated_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'mymodule' has no attribute 'deprecated_var'
I have a file called skdb and class called skmysqldb. I am trying to force reload.
I tried reloading "skdb", "skdb.skmysqldb" "skmysqldb" and none of them seem to work.
>>> from skdb import skmysqldb
>>> importlib.reload(skdb.skmysqldb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined
>>> importlib.reload(skmysqldb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 139, in reload
raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module
>>> importlib.reload(skdb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined
When you import some object using the from <module> import <obj> syntax as in
from skdb import skmysqldb
the module itself is not added to the current namespace, hence why you get a NameError when you try to do reload(skdb).
Instead try:
import skdb
importlib.reload(skdb)
Be cautious when using reload. If the module your reload imports other modules, those modules are not reloaded recursively, so depending on the exact code you can wind up in a rather broken state where it's better to just restart the whole interpreter.
I don't think this is supported, but try doing del sys.modules['mymodule'] for everything that vaguely matches. To find relevant ones, try something like [x for x in sys.modules if 'mymodule' in x].
I'm trying to define a method (let's call it hello) in main.py's Things class, from define.py.
The code I currently have is raising AttributeError: module 'runme' has no attribute 'promptMe' (full traceback below).
Here's main.py's code:
import define
class Things:
def doWhatever():
print("whatever")
Here's define.py's code:
import main
def hello():
print("Hello!")
main.Things.hello = hello()
I've tried other solutions such as def main.Things.hello: hello() and def main.Things.hello: print("Hello!") but none work.
Here's the traceback when running define.py:
Traceback (most recent call last):
File "define.py", line 5, in <module>
import main
File "/path/to/main.py", line 9, in <module>
import define
File "/path/to/define.py", line 10, in <module>
main.Things.hello = hello
AttributeError: module 'main' has no attribute 'Things'
All help would be greatly appreciated. Thanks!