python giving a E501: line too long error - python

While trying to input my API key python is giving me a line too long code
E501: line too long
What I have is
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error?

E501 is a linter error, not a Python interpreter error. Your code, in theory, should work just fine. If you want to prevent this error, simply break the value up (assuming it's a string ... you don't make that clear):
my_key = ('aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-'
'11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-'
'1aa111a0a111')
notifications_client = NotificationsAPIClient(my_key)

E501 is not a python error, rather than a PEP8 error. Meaning your line is longer than 80 chars (in your case it's 137 chars long).
Your editor or runtime are verifying that your code is correct by PEP8 rules and that's why you are getting this "error". Your Python code has actually no errors at all.
If you want your code to be PEP8 compliant I suggest:
Extract the API key to a local variable.
If it's still too long you can break up the string into multiple lines
Here is an example:
API_KEY = 'aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a' \
'-aaaa-11111aaa1a1a-aa11a1a1-0aa1-' \
'11a1-1111-1aa111a0a111'
notifications_client = NotificationsAPIClient(API_KEY)

Use \ to break your line. Like;
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-\
aa11-111a-aaaa-11111aaa1a1a-\
aa11a1a1-0aa1-11a1-1111-1aa111a0a111)

Option which doesn't involved breaking the string literal:
notifications_client = NotificationsAPIClient(
"kkkkkkkkkkkkkeeeeeeeeeeeeeeeeeeeeeeeeeeyyyyyyyyyyyyyyyyyyyyy"
)
So long as your key is <73 (minus scope indentation) characters long. If not, you'll have to split it.

Related

Python: how to get rid of non-ascii characters being read from a file

I am processing, with python, a long list of data that looks like this
The digraphs are probably due to encoding problems. (I am not sure whether these characters will be preserved in this site)
29/07/2016 04:00:12 0.125143
Now, when I read such file into a script using something like open and readlines, there is an error, reading
SyntaxError: EOL while scanning string literal
I know (or may look up usage of) replace and regex functions, but I cannot do them in my script. The biggest problem is that anywhere I include or read such strange character, error occurs, pointing on the very line it is read. So I cannot do anything to them.
Are you reading a file? If so, try to extract values using regexps, not to remove extra characters:
re.search(r'^([\d/: ]{19})', line).group(1)
re.search(r'([\d.]{7})', line).group(1)
I find that the re.findall works. (I am sorry I do not have time to test all other methods, since the significance of this job has vanished, and I even forget this question itself.)
def extract_numbers(str_i):
pat="(\d+)/(\d+)/(\d+)\D*(\d+):(\d+):(\d+)\D*(\d+)\.(\d+)"
match_h = re.findall(pat, str_i)
return match_h[0]
# ....
# `f` is the handle of the file in question
lines =f.readlines()
for l in lines:
ls_f =extract_numbers(l)
# process them....

Vexing Python syntax error

I am writing a python script using version 2.7.3. In the script a line is
toolsDir = 'tools/'
When I run this in terminal I get SyntaxError: invalid syntax on the last character in the string 'r'. I've tried renaming the string, using " as opposed to '. If I actually go into python via bash and declare the string in one line and print it I get no error.
I checked the encoding via file -i update.py and I get text/x-python; charset=us-ascii
I have used TextWrangler, nano and LeafPad as the text editors.
I have a feeling it may be something with the encoding of one of the editors. I have had this script run before without any errors.
Any advice would be greatly appreciated.
The string is 'tools/'. toolsDir is a variable. You're free to use different terminology, of course, but you'll end up confusing people trying to help you. The only r in that line is the last character of the variable name, so I assume that's the location of the error.
Most likely you've managed to introduce a fixed-width space (character code 0xA0) instead of an ordinary space. Try deleting SP=SP (all three characters) and retyping them.
Try running the code through pylint.
You probably have a syntax error on a nearby line before this one. Try commenting this line out and see if the error moves.
You might have a whitespace error, don't forget whitespace counts in python. If you've mixed tabs and spaces anywhere in your file it can throw the syntax checker off by several lines.
If you copied and pasted lines into this from any other source you may have copied whitespace in that doesn't fit with whichever convention you used.
The error was, of course, a silly one.
In one of my imports I use try: without closing or catching the error condition. pylint did not catch this and the error message did not indicate this.
If someone in the future has this triple check all opening code for syntax errors.

Syntax error with exec call in Python

Quick python question about the exec command. I'm have Python 2.7.6 and am trying to make use of the exec to run some code stored in a .txt file. I've run into a syntax error and am not entirely sure what is causing it.
Traceback (most recent call last):
File "/Users/XYZ/Desktop/parser.py", line 46, in <module>
try_code(block)
File "<string>", line 1
x = 'Hello World!'
^
SyntaxError: invalid syntax
I initially thought it was complaining about carriage returns, but when I tried to edit them .replace them with ' ' I still received this error message. I've tried variations to see what appears to be the issue and it always declares the error as the first ' or " the program encounters when it runs exec.
Here is the try_code(block) method
def try_code(block):
exec block
And the main body of the program
inputFile = open('/Users/XYZ/Desktop/test.txt', 'r+')
starter = False
finished = False
check = 1
block = ""
for val in inputFile:
starter = lookForStart(val)
finished = lookForEnd(val)
if lookForStart:
check = 1
elif finished:
try_code(block)
if check == 1:
check = 0
elif finished == False:
block = block + val
Basically I'm trying to import a file (test.txt) and then look for some embedded code in it. To make it easier I surrounded it with indicators, thus starter and finished. Then I concatenate all the hidden code into one string and call try_code on it. Then try_code attempts to execute it (it does make it there, check with print statements) and fails with the Syntax error.
As a note it works fine if I have hidden something like...
x = 5
print x
so whatever the problem is appears to be dealing with strings for some reason.
EDIT
It would appear that textedit includes some extra characters that aren't displayed normally. I rewrote the test file in a different text editor (text wrangler) and it would seem that the characters have disappeared. Thank you all very much for helping me solve my problem, I appreciate it.
It is a character encoding issue. Unless you've explicitly declared character encoding of your Python source code at the top of the file; it is 'ascii' by default on Python 2.
The code that you're trying to execute contains non-ascii quotes:
>>> print b'\xe2\x80\x98Hello World\xe2\x80\x99'.decode('utf-8')
‘Hello World’
To fix it; use ordinary single quotes instead: 'Hello World'.
You can check that block doesn't contain non-ascii characters using decode method: block.decode('ascii') it raises an exception if there are.
A gentle introduction into the topic: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
by Joel Spolsky.

What does a semicolon do?

I got a function online to help me with my current project and it had semicolons on some of the lines. I was wondering why? Is it to break the function?
def containsAny(self, strings=[]):
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
for string in strings:
for char in string:
if char in alphabet: return 1;
return 0;
The function I got online with little modification:
for string in strings:
for char in string:
if char in alphabet: return 1;
Is the above saying the following?
if char in alphabet:
return 1
break
The semicolon does nothing in the code you show.
I suspect this is someone who programs in another language (C, Java, ...) that requires semicolons at the end of statements and it's just a habit (happens to me sometimes too).
If you want to put several Python statements on the same line, you can use a semi-colon to separate them, see this Python Doc:
A suite is a group of statements controlled by a clause. A suite can
be one or more semicolon-separated simple statements on the same line
as the header, following the header’s colon, or it can be one or more
indented statements on subsequent lines
The semicolon here does not do anything. People who come from C/C++/Java/(many other language) backgrounds tend to use the semicolon out of habit.
In general the semicolon does nothing. But if you are using the Jupyter Notebook (depending on your version), you might get a figure plotted twice. The semicolon at the end of your plot command prevents this:
df.plot();
Programmers of C, C++, and Java are habituated of using a semicolon to tell the compiler that this is the end of a statement, but for Python this is not the case.
The reason is that in Python, newlines are an unambiguous way of separating code lines; this is by design, and the way this works has been thoroughly thought through. As a result, Python code is perfectly readable and unambiguous without any special end-of-statement markers (apart from the newline).
As other answers point out, the semicolon does nothing there. It's a separator (e.g. print 1;print 2). But it does not work like this: def func():print 1;print 2;;print'Defined!' (;; is a syntax error). Out of habit, people tend to use it (as it is required in languages such as C/Java...).

Why not python implicit line continuation on period?

Is there any reason Python does not allow implicit line continuations after (or before) periods? That is
data.where(lambda d: e.name == 'Obama').
count()
data.where(lambda d: e.name == 'Obama')
.count()
Does this conflict with some feature of Python? With the rise of method chaining APIs this seems like a nice feature.
Both of those situations can lead to valid, complete constructs, so continuing on them would complicate the parser.
print 3.
1415926
print 'Hello, world'
.lower()
Python allow line continuations within parentheticals (), so you might try:
(data.where(lambda d: e.name == 'Obama').
count())
I know that's not answering your question ("why?"), but maybe it's helpful.
Use a '\' at the end. (looks ugly though)
data.where(lambda d: e.name == 'Obama').\
count()
Not sure about after periods, but in your example the newline before a period leads to the first line being a valid statement on its own. Then Python would have to look ahead to the second line to know whether the first line was a statement or not.
One of the goals when defining the language syntax was to be able to parse it without having ambiguities that require looking ahead like that.
It'd get annoying in the interactive interpreter if you had to press enter twice after every single line just so Python knew you'd finished your statement and weren't going to put a .foo() after it.
In the cases where a period could be leading in to a method call, it will always(?) be a syntax error for it to just occur at the end of a line by itself. So it would be unambiguous to read it as starting a continuation.
However, Python generally speaking doesn't continue a line just because there's an incomplete binary operator there. For instance, the following is not valid:
2 +
4
In the second example, the first line is valid by itself and it would be really inconsistent for Python to look for a following line "just in case" there is one.
I would just break after the opening paren of the method call.
{Because python uses line breaks to end statements, not depending on braces or semi-colins;}

Categories