Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

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

Merged
merged 5 commits into from

3 participants

@takluyver
Owner

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.

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 Owner
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
Owner

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 from
@fperez fperez referenced this pull request from a commit
Commit has since been removed from the repository and is no longer available.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
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.