Skip to content

Loading…

Add coding header when notebook exported to .py file. #1158

Merged
merged 5 commits into from

3 participants

@takluyver
IPython member

Closes gh-1156

We probably want to strip the encoding declaration out when we load a .py file, as well. I'll add that to this PR.

@fperez fperez commented on an outdated diff
IPython/nbformat/v2/nbpy.py
@@ -111,7 +114,7 @@ class PyWriter(NotebookWriter):
def writes(self, nb, **kwargs):
lines = []
- lines.extend([u'# <nbformat>2</nbformat>',''])
+ lines.extend([u'# coding: utf-8', u'# <nbformat>2</nbformat>',''])
@fperez IPython member
fperez added a note

I think this should be done in two separate lines. Let' s not mix encoding with nbformat info. Instead, initialize the lines list with the encoding declaration:

lines = ['# coding: utf-8'']
# rest of the code as it was before this PR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@takluyver
IPython member

Updated.

@bfroehle

Looks good to me, is there any benefit to # -*- coding: utf-8 -*- as Fernando originally suggested over # coding: utf-8 ?

@fperez fperez merged commit 688cc09 into ipython:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Showing with 7 additions and 3 deletions.
  1. +5 −2 IPython/nbformat/v2/nbpy.py
  2. +2 −1 IPython/nbformat/v2/tests/nbexamples.py
View
7 IPython/nbformat/v2/nbpy.py
@@ -16,6 +16,7 @@
# Imports
#-----------------------------------------------------------------------------
+import re
from .rwbase import NotebookReader, NotebookWriter
from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
@@ -23,6 +24,8 @@
# Code
#-----------------------------------------------------------------------------
+_encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
+
class PyReaderError(Exception):
pass
@@ -38,7 +41,7 @@ def to_notebook(self, s, **kwargs):
cell_lines = []
state = u'codecell'
for line in lines:
- if line.startswith(u'# <nbformat>'):
+ if line.startswith(u'# <nbformat>') or _encoding_declaration_re.match(line):
pass
elif line.startswith(u'# <codecell>'):
cell = self.new_cell(state, cell_lines)
@@ -110,7 +113,7 @@ def split_lines_into_blocks(self, lines):
class PyWriter(NotebookWriter):
def writes(self, nb, **kwargs):
- lines = []
+ lines = [u'# -*- coding: utf-8 -*-']
lines.extend([u'# <nbformat>2</nbformat>',''])
for ws in nb.worksheets:
for cell in ws.cells:
View
3 IPython/nbformat/v2/tests/nbexamples.py
@@ -81,7 +81,8 @@
metadata=md
)
-nb0_py = """# <nbformat>2</nbformat>
+nb0_py = """# -*- coding: utf-8 -*-
+# <nbformat>2</nbformat>
# <htmlcell>
Something went wrong with that request. Please try again.