Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: encoding declaration in Unicode string

If I try to use a magic comment like #coding=utf-8 on top of a file, here's what happens:

Traceback (most recent call last):
  File <string>, line 0
SyntaxError: encoding declaration in Unicode string

I really haven't done anything wrong. Here is the code:

#coding=utf-8

string = raw_input()
chars = {}
for i in string:
    if i in chars:
        chars[i] += 1
    else:
        chars[i] = 0
print chars

I use repl.it.

like image 696
EKons Avatar asked Aug 01 '26 06:08

EKons


1 Answers

You omitted something from your question: You are using exec to execute this code. And you passed a Unicode object to exec, which means you already have stated that the source is Unicode text:

>>> code = '''\
... # coding=utf8
... print 'hello world!'
... '''
>>> exec code
hello world!
>>> exec code.decode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 0
SyntaxError: encoding declaration in Unicode string

You can't use a PEP 263 declaration in Unicode text passed to exec.

If you are using a 'custom' environment like repl.it, then yes, such environments invariably use tricks like exec to execute code, and they load the source code as Unicode from your browser. See the actual code used, which passes JSON-sourced strings to exec (where such strings are always going to be unicode strings).

like image 53
Martijn Pieters Avatar answered Aug 03 '26 21:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!