Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade to python 3.5+ syntax, add autoformat #11768

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion IPython/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
from .utils.frame import extract_module_locals

# Release data
__author__ = '%s <%s>' % (release.author, release.author_email)
__author__ = '{} <{}>'.format(release.author, release.author_email)
__license__ = release.license
__version__ = release.version
version_info = release.version_info
Expand Down
8 changes: 4 additions & 4 deletions IPython/core/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class AliasError(Exception):
class InvalidAliasError(AliasError):
pass

class Alias(object):
class Alias:
"""Callable object storing the details of one alias.

Instances are registered as magic functions to allow use of aliases.
Expand Down Expand Up @@ -174,14 +174,14 @@ def __call__(self, rest=''):
if cmd.find('%%s') >= 1:
cmd = cmd.replace('%%s', '%s')
# Simple, argument-less aliases
cmd = '%s %s' % (cmd, rest)
cmd = '{} {}'.format(cmd, rest)
else:
# Handle aliases with positional arguments
args = rest.split(None, nargs)
if len(args) < nargs:
raise UsageError('Alias <%s> requires %s arguments, %s given.' %
(self.name, nargs, len(args)))
cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
cmd = '{} {}'.format(cmd % tuple(args[:nargs]),' '.join(args[nargs:]))

self.shell.system(cmd)

Expand All @@ -196,7 +196,7 @@ class AliasManager(Configurable):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)

def __init__(self, shell=None, **kwargs):
super(AliasManager, self).__init__(shell=shell, **kwargs)
super().__init__(shell=shell, **kwargs)
# For convenient access
self.linemagics = self.shell.magics_manager.magics['line']
self.init_aliases()
Expand Down
20 changes: 10 additions & 10 deletions IPython/core/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ def load_subconfig(self, fname, path=None, profile=None):
except ProfileDirError:
return
path = profile_dir.location
return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
return super().load_subconfig(fname, path=path)

class BaseIPythonApplication(Application):

name = u'ipython'
description = Unicode(u'IPython: an enhanced interactive Python shell.')
name = 'ipython'
description = Unicode('IPython: an enhanced interactive Python shell.')
version = Unicode(release.version)

aliases = base_aliases
Expand All @@ -119,15 +119,15 @@ class BaseIPythonApplication(Application):
config_file_name = Unicode()
@default('config_file_name')
def _config_file_name_default(self):
return self.name.replace('-','_') + u'_config.py'
return self.name.replace('-','_') + '_config.py'
@observe('config_file_name')
def _config_file_name_changed(self, change):
if change['new'] != change['old']:
self.config_file_specified.add(change['new'])

# The directory that contains IPython's builtin profiles.
builtin_profile_dir = Unicode(
os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
os.path.join(get_ipython_package_dir(), 'config', 'profile', 'default')
)

config_file_paths = List(Unicode())
Expand All @@ -151,14 +151,14 @@ def _extra_config_file_changed(self, change):
self.config_file_specified.add(new)
self.config_files.append(new)

profile = Unicode(u'default',
profile = Unicode('default',
help="""The IPython profile to use."""
).tag(config=True)

@observe('profile')
def _profile_changed(self, change):
self.builtin_profile_dir = os.path.join(
get_ipython_package_dir(), u'config', u'profile', change['new']
get_ipython_package_dir(), 'config', 'profile', change['new']
)

ipython_dir = Unicode(
Expand Down Expand Up @@ -219,7 +219,7 @@ def _config_files_default(self):

@catch_config_error
def __init__(self, **kwargs):
super(BaseIPythonApplication, self).__init__(**kwargs)
super().__init__(**kwargs)
# ensure current working directory exists
try:
os.getcwd()
Expand All @@ -240,7 +240,7 @@ def initialize_subcommand(self, subc, argv=None):
"in future versions.".format(sub=subc))
self.log.warning("You likely want to use `jupyter {sub}` in the "
"future".format(sub=subc))
return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
return super().initialize_subcommand(subc, argv)

def init_crash_handler(self):
"""Create a crash handler, typically setting sys.excepthook to it."""
Expand Down Expand Up @@ -274,7 +274,7 @@ def _ipython_dir_changed(self, change):
sys.path.append(str_path)
ensure_dir_exists(new)
readme = os.path.join(new, 'README')
readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
readme_src = os.path.join(get_ipython_package_dir(), 'config', 'profile', 'README')
if not os.path.exists(readme) and os.path.exists(readme_src):
shutil.copy(readme_src, readme)
for d in ('extensions', 'nbextensions'):
Expand Down
2 changes: 1 addition & 1 deletion IPython/core/autocall.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
# Code
#-----------------------------------------------------------------------------

class IPyAutocall(object):
class IPyAutocall:
""" Instances of this class are always autocalled

This happens regardless of 'autocall' variable state. Use this to
Expand Down
6 changes: 3 additions & 3 deletions IPython/core/builtin_trap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
from traitlets import Instance


class __BuiltinUndefined(object): pass
class __BuiltinUndefined: pass
BuiltinUndefined = __BuiltinUndefined()

class __HideBuiltin(object): pass
class __HideBuiltin: pass
HideBuiltin = __HideBuiltin()


Expand All @@ -23,7 +23,7 @@ class BuiltinTrap(Configurable):
allow_none=True)

def __init__(self, shell=None):
super(BuiltinTrap, self).__init__(shell=shell, config=None)
super().__init__(shell=shell, config=None)
self._orig_builtins = {}
# We define this to track if a single BuiltinTrap is nested.
# Only turn off the trap when the outermost call to __exit__ is made.
Expand Down
2 changes: 1 addition & 1 deletion IPython/core/compilerop.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def code_name(code, number=0):
# Include the number and 12 characters of the hash in the name. It's
# pretty much impossible that in a single session we'll have collisions
# even with truncated hashes, and the full one makes tracebacks too long
return '<ipython-input-{0}-{1}>'.format(number, hash_digest[:12])
return '<ipython-input-{}-{}>'.format(number, hash_digest[:12])

#-----------------------------------------------------------------------------
# Classes and functions
Expand Down
48 changes: 24 additions & 24 deletions IPython/core/completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
GREEDY_DELIMS = ' =\r\n'


class CompletionSplitter(object):
class CompletionSplitter:
"""An object to split an input line in a manner similar to readline.

By having our own implementation, we can expose readline-like completion in
Expand Down Expand Up @@ -627,7 +627,7 @@ def __init__(self, namespace=None, global_namespace=None, **kwargs):
else:
self.global_namespace = global_namespace

super(Completer, self).__init__(**kwargs)
super().__init__(**kwargs)

def complete(self, text, state):
"""Return the next possible completion for 'text'.
Expand Down Expand Up @@ -729,7 +729,7 @@ def attr_matches(self, text):
pass
# Build match list to return
n = len(attr)
return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
return ["{}.{}".format(expr, w) for w in words if w[:n] == attr ]


def get__all__entries(obj):
Expand Down Expand Up @@ -807,7 +807,7 @@ def match_dict_keys(keys: List[str], prefix: str, delims: str):
rem_repr = rem_repr.replace('"', '\\"')

# then reinsert prefix from start of token
matched.append('%s%s' % (token_prefix, rem_repr))
matched.append('{}{}'.format(token_prefix, rem_repr))
return quote, token_start, matched


Expand Down Expand Up @@ -869,7 +869,7 @@ def position_to_cursor(text:str, offset:int)->Tuple[int, int]:

"""

assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
assert 0 <= offset <= len(text) , "0 <= {} <= {}".format(offset , len(text))

before = text[:offset]
blines = before.split('\n') # ! splitnes trim trailing \n
Expand All @@ -886,7 +886,7 @@ def _safe_isinstance(obj, module, class_name):


def back_unicode_name_matches(text):
u"""Match unicode characters back to unicode name
"""Match unicode characters back to unicode name

This does ``☃`` -> ``\\snowman``

Expand All @@ -898,22 +898,22 @@ def back_unicode_name_matches(text):
Used on Python 3 only.
"""
if len(text)<2:
return u'', ()
return '', ()
maybe_slash = text[-2]
if maybe_slash != '\\':
return u'', ()
return '', ()

char = text[-1]
# no expand on quote for completion in strings.
# nor backcomplete standard ascii keys
if char in string.ascii_letters or char in ['"',"'"]:
return u'', ()
return '', ()
try :
unic = unicodedata.name(char)
return '\\'+char,['\\'+unic]
except KeyError:
pass
return u'', ()
return '', ()

def back_latex_name_matches(text:str):
"""Match latex characters back to unicode name
Expand All @@ -923,24 +923,24 @@ def back_latex_name_matches(text:str):
Used on Python 3 only.
"""
if len(text)<2:
return u'', ()
return '', ()
maybe_slash = text[-2]
if maybe_slash != '\\':
return u'', ()
return '', ()


char = text[-1]
# no expand on quote for completion in strings.
# nor backcomplete standard ascii keys
if char in string.ascii_letters or char in ['"',"'"]:
return u'', ()
return '', ()
try :
latex = reverse_latex_symbol[char]
# '\\' replace the \ as well
return '\\'+char,[latex]
except KeyError:
pass
return u'', ()
return '', ()


def _formatparamchildren(parameter) -> str:
Expand Down Expand Up @@ -1174,9 +1174,9 @@ def file_matches(self, text):
# when escaped with backslash
if text.startswith('!'):
text = text[1:]
text_prefix = u'!'
text_prefix = '!'
else:
text_prefix = u''
text_prefix = ''

text_until_cursor = self.text_until_cursor
# track strings with open quotes
Expand Down Expand Up @@ -1284,9 +1284,9 @@ def magic_config_matches(self, text:str) -> List[str]:

if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
# get all configuration classes
classes = sorted(set([ c for c in self.shell.configurables
classes = sorted({ c for c in self.shell.configurables
if c.__class__.class_traits(config=True)
]), key=lambda x: x.__class__.__name__)
}, key=lambda x: x.__class__.__name__)
classnames = [ c.__class__.__name__ for c in classes ]

# return all classnames if config or %config is given
Expand Down Expand Up @@ -1554,7 +1554,7 @@ def python_func_kw_matches(self,text):
# Remove used named arguments from the list, no need to show twice
for namedArg in set(namedArgs) - usedNamedArgs:
if namedArg.startswith(text):
argMatches.append(u"%s=" %namedArg)
argMatches.append("%s=" %namedArg)
except:
pass

Expand Down Expand Up @@ -1669,7 +1669,7 @@ def get_keys(obj):
return [leading + k + suf for k in matches]

def unicode_name_matches(self, text):
u"""Match Latex-like syntax for unicode characters base
"""Match Latex-like syntax for unicode characters base
on the name of the character.

This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
Expand All @@ -1689,11 +1689,11 @@ def unicode_name_matches(self, text):
return '\\'+s,[unic]
except KeyError:
pass
return u'', []
return '', []


def latex_matches(self, text):
u"""Match Latex syntax for unicode characters.
"""Match Latex syntax for unicode characters.

This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``

Expand All @@ -1711,7 +1711,7 @@ def latex_matches(self, text):
# a full list of options \al -> [\aleph, \alpha]
matches = [k for k in latex_symbols if k.startswith(s)]
return s, matches
return u'', []
return '', []

def dispatch_custom_completer(self, text):
if not self.custom_completers:
Expand Down Expand Up @@ -2089,4 +2089,4 @@ def fwd_unicode_match(self, text:str) -> Tuple[str, list]:

# if text does not start with slash
else:
return u'', ()
return '', ()
2 changes: 1 addition & 1 deletion IPython/core/crashhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
"""


class CrashHandler(object):
class CrashHandler:
"""Customizable crash handlers for IPython applications.

Instances of this class provide a :meth:`__call__` method which can be
Expand Down