3

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.

8
  • it's encoding, not coding. Commented Aug 25, 2016 at 10:06
  • @DeepSpace See here. Of course it can be coding! Commented Aug 25, 2016 at 10:07
  • 1
    @DeepSpace: no it isn't. It could be decoding, or flubcoding, or just coding. The regex used doesn't care. See What's the difference between 'coding=utf8' and '-*- coding: utf-8 -*-'? Commented Aug 25, 2016 at 10:08
  • @MartijnPieters Thanks, good to know! Commented Aug 25, 2016 at 10:09
  • Are you using exec to run this by any chance? The error message would not make sense otherwise. Commented Aug 25, 2016 at 10:10

1 Answer 1

13

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).

Sign up to request clarification or add additional context in comments.

4 Comments

I think the interpreter uses exec. Thanks in advance! +1
@ΈρικΚωνσταντόπουλος: it does, on Unicode strings loaded from JSON; the actual script is readily available when reading sys.argv[0].
@ΈρικΚωνσταντόπουλος: I didn't mean to imply you didn't, sorry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.