How is this invalid syntax? - python

I have a python module that consists of many function definitions, all static. Then at the end I added a class definition however, the interpreter presents me with the following error:
Traceback (most recent call last):
File "~/file.py", line 136
class InvalidPredicateError(Exception):
^
SyntaxError: invalid syntax
I don't see a problem with this at all. Is it because I'm trying to define a class in a static module?

You have an error on the line(s) before the class. For example:
$ cat -n pyinvclass.py
1 def f():
2 return (1, 2
3
4 class InvalidPredicateError(Exception):
5 pass
$ python pyinvclass.py
File "pyinvclass.py", line 4
class InvalidPredicateError(Exception):
^
SyntaxError: invalid syntax

Related

Why does a python script behaves differently when it is run in pycharm and when it is run from a command prompt?

I'm getting an error when I run a script from the Linux command prompt(bash), but when I run the same script in the Pycharm directly, it works fine.
Here is the code:
class EncodeKey:
def __new__(cls, *args):
if len(args) == 1:
return cls.generate_encode_key(args[0].upper())
return cls.get_encode_key(args)
...
...
if __name__ == '__main__':
encode_key = EncodeKey(*["something"])
print(encode_key)
As I already told, in the Pycharm the script works fine without any errors, but here is what I'm getting when the script is run from the command prompt:
user#machine:~/my/path/to/the/script$ python py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Or:
user#machine:~/my/path/to/the/script$ ls -lh
...
-rwxrwxr-x 1 user user 3.2K Jun 20 19:12 py.py
...
user#machine:~/my/path/to/the/script$ ./py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Of, course, I didn't find any solutions on such an unusual problem. Any ideas why is that happening ? And how to solve it ? Thanks !
If you've installed python in the default way, the python command uses Python 2. To interperet with Python 3, use the command python3:
user#machine:~/my/path/to/the/script$ python3 py.py
The program errors in Python 2 because old-style classes, the default in Python 2, do not support __new__. If you need to support Python 2, make your class new-style by extending object:
class EncodeKey(object):
Your code will still work in Python 3 if you do this.

Can't instantiate objects using cli python interpreter

Can't instantiate objects using python interpreter, please help.
So inside of my python file expresser.py I have something like
class Expresser:
def __init__(self):
pass
...
Now when I type in the terminal
python
and then
>>> import expresser
>>> test_object = Expresser()
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Expresser' is not defined
I'm using PyCharm
when I type where python I get three diff locations so I suspect that but don't know how to rectify
I guess you meant:
from expresser import Expresser
Or:
from expresser import *

Using type stubs for Python stdlib with mypy

Consider the following MWE:
import hashlib
def tstfun(h: hashlib._hashlib.HASH):
print(h)
h = hashlib.md5()
tstfun(h)
# reveal_type(h)
Running this as-is yields - no surprise:
$ python mypytest.py
<md5 _hashlib.HASH object # 0x7fa645dedd90>
But checking this with mypy fails with:
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
Found 1 error in 1 file (checked 1 source file)
Now, revealing the type on h (commenting in that reveal_type line):
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
mypytest.py:10: note: Revealed type is 'hashlib._Hash'
Found 1 error in 1 file (checked 1 source file)
Well, ok, then changing the type hint from hashlib._hashlib.HASH to hashlib._Hash:
$ python mypytest.py
Traceback (most recent call last):
File "/radarugs/hintze/s4-cnc-tools/mypytest.py", line 4, in <module>
def tstfun(h: hashlib._HASH):
AttributeError: module 'hashlib' has no attribute '_HASH'
$ mypy mypytest.py
mypytest.py:4: error: Name 'hashlib._HASH' is not defined
Found 1 error in 1 file (checked 1 source file)
...which is the worst outcome.
How to check if the type stubs for the hashlib are correctly found and used by mypy? What else to check? What do I get wrong?
According to the traceback, you used hashlib._HASH.
With this code:
import hashlib
def tstfun(h: hashlib._Hash):
print(h)
h = hashlib.md5()
tstfun(h)
Mypy reports: Success: no issues found in 1 source file
Using hashlib._Hash is correct, but you also need to from __future__ import annotations if you don't want to use quotes. See https://github.com/python/typeshed/issues/2928
from __future__ import annotations
import hashlib
def tstfun(h: hashlib._Hash):
print(h)
h = hashlib.md5()
tstfun(h)
N.B.: __future__.annotations is available starting in python 3.7.0b1. See https://docs.python.org/3/library/__future__.html

Weird invalid syntax in python

I'm trying to run a python script in the Mac Terminal with python test.py.
The problem is that I getting this error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
import agent as a
File "/home/test/script/agent.py", line 5
budget: None
^
SyntaxError: invalid syntax
why this line budget: Noneis giving a SyntaxError?
the original code:
class Agent:
budget: None
budget_left: None
(....)
When I run the script in PyCharm works just fine.
It's giving a syntax error because, well, that is invalid syntax. You don't define attributes like that; you need to use assignment.
class Agent:
budget = None
budget_left = None
Note, though, defining these as class attributes probably isn't what you want.
Just put '=' for the variables and you are done.
budget = None
Read this for more on the topic:
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3

Python assert -- improved introspection of failure?

This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names):
$ python -c "assert 6-(3*2)"
[...]
AssertionError
Is there a better assert implementation in Python that is more fancy? It must not introduce additional overhead over execution (except when assert fails) .. and must turn off if -O flag is used.
Edit: I know about assert's second argument as a string. I don't want to write one .. as that is encoded in the expression that is being asserted. DRY (Don't Repeat Yourself).
Install your of function as sys.excepthook -- see the docs. Your function, if the second argument is AssertionError, can introspect to your heart's contents; in particular, through the third argument, the traceback, it can get the frame and exact spot in which the assert failed, getting the failing exception through the source or bytecode, the value of all relevant variables, etc. Module inspect helps.
Doing it in full generality is quite a piece of work, but depending on what constraints you're willing to accept in how you write your asserts it can be lightened substantially (e.g. restricting them to only local or global variables makes introspection easier than if nonlocal variables of a closure could be involved, and so forth).
You can attach a message to an assert:
assert 6-(3*2), "always fails"
The message can also be built dynamically:
assert x != 0, "x is not equal to zero (%d)" % x
See The assert statement in the Python documentation for more information.
As #Mark Rushakoff said nose can evaluate failed asserts. It works on the standard assert too.
# test_error_reporting.py
def test():
a,b,c = 6, 2, 3
assert a - b*c
nosetests' help:
$ nosetests --help|grep -B2 assert
-d, --detailed-errors, --failure-detail
Add detail to error output by attempting to evaluate
failed asserts [NOSE_DETAILED_ERRORS]
Example:
$ nosetests -d
F
======================================================================
FAIL: test_error_reporting.test
----------------------------------------------------------------------
Traceback (most recent call last):
File "..snip../site-packages/nose/case.py", line 183, in runTest
self.test(*self.arg)
File "..snip../test_error_reporting.py", line 3, in test
assert a - b*c
AssertionError:
6,2,3 = 6, 2, 3
>> assert 6 - 2*3
----------------------------------------------------------------------
Ran 1 test in 0.089s
FAILED (failures=1)
The nose testing suite applies introspection to asserts.
However, AFAICT, you have to call their asserts to get the introspection:
import nose
def test1():
nose.tools.assert_equal(6, 5+2)
results in
C:\temp\py>C:\Python26\Scripts\nosetests.exe -d test.py
F
======================================================================
FAIL: test.test1
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\nose-0.11.1-py2.6.egg\nose\case.py", line
183, in runTest
self.test(*self.arg)
File "C:\temp\py\test.py", line 3, in test1
nose.tools.assert_equal(6, 5+2)
AssertionError: 6 != 7
>> raise self.failureException, \
(None or '%r != %r' % (6, 7))
Notice the AssertionError there. When my line was just assert 6 == 5+2, I would get:
C:\temp\py>C:\Python26\Scripts\nosetests.exe -d test.py
F
======================================================================
FAIL: test.test1
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\nose-0.11.1-py2.6.egg\nose\case.py", line
183, in runTest
self.test(*self.arg)
File "C:\temp\py\test.py", line 2, in test1
assert 6 == 5 + 2
AssertionError:
>> assert 6 == 5 + 2
Also, I'm not sure offhand if their asserts are skipped with -O, but that would be a very quick check.
I coded a replacement for sys.excepthook (which is called for any unhandled exception) which is a bit more fancy than the standard one. It will analyze the line where the exception occured and print all variables which are referred to in this line (it does not print all local variables because that might be too much noise - also, maybe the important var is global or so).
I called it py_better_exchook (perfect name) and it's here.
Example file:
a = 6
def test():
unrelated_var = 43
b,c = 2, 3
assert a - b*c
import better_exchook
better_exchook.install()
test()
Output:
$ python test_error_reporting.py
EXCEPTION
Traceback (most recent call last):
File "test_error_reporting.py", line 12, in <module>
line: test()
locals:
test = <local> <function test at 0x7fd91b1a05f0>
File "test_error_reporting.py", line 7, in test
line: assert a - b*c
locals:
a = <global> 6
b = <local> 2
c = <local> 3
AssertionError
There are a few other alternatives:
(Presented here) https://github.com/albertz/py_better_exchook/
https://github.com/patrys/great-justice
Nose does something similar for assertion failures, see here.
IPython has something similar (this). Do this: from IPython.core import ultratb; sys.excepthook = ultratb.VerboseTB().
Ka-Ping Yee's "cgitb.py", which is part of Python, see here, code here.
Add a message to your assertion, which will be displayed if the assertion fails:
$ python -c "assert 6-(3*2), '6-(3*2)'"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AssertionError: 6-(3*2)
The only way I can think of to provide this automatically would be to contain the assertion in a procedure call, and then inspect the stack to get the source code for that line. The additional call would, unfortunately, introduce overhead into the test and would not be disabled with -O.
It sounds like what you really want to do is to set up a debugger breakpoint just before the assert and inspect from your favorite debugger as much as you like.

Categories