X Tutup
Skip to content

Commit b23e191

Browse files
get source in unicode in python 2 and 3
1 parent 4f079d9 commit b23e191

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

bpython/inspection.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,3 +270,18 @@ def is_callable(obj):
270270
return isinstance(obj, collections.Callable)
271271
else:
272272
return callable(obj)
273+
274+
275+
def get_encoding(obj):
276+
for line in inspect.getsourcelines(obj)[0][:2]:
277+
m = re.search(r'coding[:=]\s*([-\w.]+)', line)
278+
if m:
279+
return m.group(1)
280+
return 'ascii'
281+
282+
283+
def get_source_unicode(obj):
284+
"""Returns a decoded source of object"""
285+
if py3:
286+
return inspect.getsource(obj)
287+
return inspect.getsource(obj).decode(get_encoding(obj))

bpython/repl.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -466,9 +466,10 @@ def get_args(self):
466466
return False
467467

468468
def get_source_of_current_name(self):
469-
"""Return the source code of the object which is bound to the
469+
"""Return the unicode source code of the object which is bound to the
470470
current name in the current input line. Throw `SourceNotFound` if the
471-
source cannot be found. Returns bytestring in py2, unicode in py3."""
471+
source cannot be found."""
472+
472473
obj = self.current_func
473474
try:
474475
if obj is None:
@@ -477,7 +478,7 @@ def get_source_of_current_name(self):
477478
raise SourceNotFound(_("Nothing to get source of"))
478479
if inspection.is_eval_safe_name(line):
479480
obj = self.get_object(line)
480-
return inspect.getsource(obj)
481+
return inspection.get_source_unicode(obj)
481482
except (AttributeError, NameError) as e:
482483
msg = _("Cannot get source: %s") % (str(e), )
483484
except IOError as e:

bpython/test/test_inspection.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,11 @@ def spam(eggs=23, foobar="yay"):
6161
self.assertEqual(repr(defaults[0]), "23")
6262
self.assertEqual(repr(defaults[1]), "'yay'")
6363

64+
def test_get_encoding(self):
65+
self.assertEqual(inspection.get_encoding(inspection), 'ascii')
66+
from bpython.test import test_curtsies_painting
67+
self.assertEqual(inspection.get_encoding(test_curtsies_painting), 'utf8')
68+
69+
6470
if __name__ == '__main__':
6571
unittest.main()

0 commit comments

Comments
 (0)
X Tutup