Skip to content

Commit ff0ee83

Browse files
committed
Apply new-style str format
1 parent deb38ec commit ff0ee83

10 files changed

Lines changed: 49 additions & 49 deletions

File tree

docs/source/conf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@
4242
master_doc = 'index'
4343

4444
# General information about the project.
45-
project = u'python-sqlparse'
46-
copyright = u'%s, Andi Albrecht' % datetime.date.today().strftime('%Y')
45+
project = 'python-sqlparse'
46+
copyright = '{:%Y}, Andi Albrecht'.format(datetime.date.today())
4747

4848
# The version info for the project you're documenting, acts as replacement for
4949
# |version| and |release|, also used in various other places throughout the
@@ -177,8 +177,8 @@
177177
# Grouping the document tree into LaTeX files. List of tuples
178178
# (source start file, target name, title, author, documentclass [howto/manual]).
179179
latex_documents = [
180-
('index', 'python-sqlparse.tex', ur'python-sqlparse Documentation',
181-
ur'Andi Albrecht', 'manual'),
180+
('index', 'python-sqlparse.tex', 'python-sqlparse Documentation',
181+
'Andi Albrecht', 'manual'),
182182
]
183183

184184
# The name of an image file (relative to this directory) to place at the top of

examples/column_defs_lowlevel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,5 @@ def extract_definitions(token_list):
4949
columns = extract_definitions(par)
5050

5151
for column in columns:
52-
print('NAME: %-12s DEFINITION: %s' % (column[0],
53-
''.join(str(t) for t in column[1:])))
52+
print('NAME: {name:10} DEFINITION: {definition}'.format(
53+
name=column[0], definition=''.join(str(t) for t in column[1:])))

examples/extract_table_names.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,6 @@
1212
# See:
1313
# http://groups.google.com/group/sqlparse/browse_thread/thread/b0bd9a022e9d4895
1414

15-
sql = """
16-
select K.a,K.b from (select H.b from (select G.c from (select F.d from
17-
(select E.e from A, B, C, D, E), F), G), H), I, J, K order by 1,2;
18-
"""
19-
2015
import sqlparse
2116
from sqlparse.sql import IdentifierList, Identifier
2217
from sqlparse.tokens import Keyword, DML
@@ -59,10 +54,16 @@ def extract_table_identifiers(token_stream):
5954
yield item.value
6055

6156

62-
def extract_tables():
57+
def extract_tables(sql):
6358
stream = extract_from_part(sqlparse.parse(sql)[0])
6459
return list(extract_table_identifiers(stream))
6560

6661

6762
if __name__ == '__main__':
68-
print('Tables: %s' % ', '.join(extract_tables()))
63+
sql = """
64+
select K.a,K.b from (select H.b from (select G.c from (select F.d from
65+
(select E.e from A, B, C, D, E), F), G), H), I, J, K order by 1,2;
66+
"""
67+
68+
tables = ', '.join(extract_tables(sql))
69+
print('Tables: {0}'.format(tables))

setup.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@
2121
def get_version():
2222
"""Parse __init__.py for version number instead of importing the file."""
2323
VERSIONFILE = 'sqlparse/__init__.py'
24-
verstrline = open(VERSIONFILE, "rt").read()
2524
VSRE = r'^__version__ = [\'"]([^\'"]*)[\'"]'
25+
with open(VERSIONFILE) as f:
26+
verstrline = f.read()
2627
mo = re.search(VSRE, verstrline, re.M)
2728
if mo:
2829
return mo.group(1)
29-
else:
30-
raise RuntimeError('Unable to find version string in %s.'
31-
% (VERSIONFILE,))
30+
raise RuntimeError('Unable to find version in {fn}'.format(fn=VERSIONFILE))
3231

3332

3433
LONG_DESCRIPTION = """

sqlparse/filters/output.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def _process(self, stream, varname, has_nl):
2222
def process(self, stmt):
2323
self.count += 1
2424
if self.count > 1:
25-
varname = '%s%d' % (self.varname, self.count)
25+
varname = '{f.varname}{f.count}'.format(f=self)
2626
else:
2727
varname = self.varname
2828

sqlparse/filters/right_margin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def _process(self, group, stream):
3838
indent = match.group()
3939
else:
4040
indent = ''
41-
yield sql.Token(T.Whitespace, '\n%s' % indent)
41+
yield sql.Token(T.Whitespace, '\n{0}'.format(indent))
4242
self.line = indent
4343
self.line += val
4444
yield token

sqlparse/formatter.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,61 +15,65 @@ def validate_options(options):
1515
"""Validates options."""
1616
kwcase = options.get('keyword_case')
1717
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
18-
raise SQLParseError('Invalid value for keyword_case: %r' % kwcase)
18+
raise SQLParseError('Invalid value for keyword_case: '
19+
'{0!r}'.format(kwcase))
1920

2021
idcase = options.get('identifier_case')
2122
if idcase not in [None, 'upper', 'lower', 'capitalize']:
22-
raise SQLParseError('Invalid value for identifier_case: %r' % idcase)
23+
raise SQLParseError('Invalid value for identifier_case: '
24+
'{0!r}'.format(idcase))
2325

2426
ofrmt = options.get('output_format')
2527
if ofrmt not in [None, 'sql', 'python', 'php']:
26-
raise SQLParseError('Unknown output format: %r' % ofrmt)
28+
raise SQLParseError('Unknown output format: '
29+
'{0!r}'.format(ofrmt))
2730

2831
strip_comments = options.get('strip_comments', False)
2932
if strip_comments not in [True, False]:
30-
raise SQLParseError('Invalid value for strip_comments: %r'
31-
% strip_comments)
33+
raise SQLParseError('Invalid value for strip_comments: '
34+
'{0!r}'.format(strip_comments))
3235

3336
space_around_operators = options.get('use_space_around_operators', False)
3437
if space_around_operators not in [True, False]:
35-
raise SQLParseError('Invalid value for use_space_around_operators: %r'
36-
% space_around_operators)
38+
raise SQLParseError('Invalid value for use_space_around_operators: '
39+
'{0!r}'.format(space_around_operators))
3740

3841
strip_ws = options.get('strip_whitespace', False)
3942
if strip_ws not in [True, False]:
40-
raise SQLParseError('Invalid value for strip_whitespace: %r'
41-
% strip_ws)
43+
raise SQLParseError('Invalid value for strip_whitespace: '
44+
'{0!r}'.format(strip_ws))
4245

4346
truncate_strings = options.get('truncate_strings')
4447
if truncate_strings is not None:
4548
try:
4649
truncate_strings = int(truncate_strings)
4750
except (ValueError, TypeError):
48-
raise SQLParseError('Invalid value for truncate_strings: %r'
49-
% truncate_strings)
51+
raise SQLParseError('Invalid value for truncate_strings: '
52+
'{0!r}'.format(truncate_strings))
5053
if truncate_strings <= 1:
51-
raise SQLParseError('Invalid value for truncate_strings: %r'
52-
% truncate_strings)
54+
raise SQLParseError('Invalid value for truncate_strings: '
55+
'{0!r}'.format(truncate_strings))
5356
options['truncate_strings'] = truncate_strings
5457
options['truncate_char'] = options.get('truncate_char', '[...]')
5558

5659
reindent = options.get('reindent', False)
5760
if reindent not in [True, False]:
58-
raise SQLParseError('Invalid value for reindent: %r'
59-
% reindent)
61+
raise SQLParseError('Invalid value for reindent: '
62+
'{0!r}'.format(reindent))
6063
elif reindent:
6164
options['strip_whitespace'] = True
6265

6366
reindent_aligned = options.get('reindent_aligned', False)
6467
if reindent_aligned not in [True, False]:
65-
raise SQLParseError('Invalid value for reindent_aligned: %r'
66-
% reindent)
68+
raise SQLParseError('Invalid value for reindent_aligned: '
69+
'{0!r}'.format(reindent))
6770
elif reindent_aligned:
6871
options['strip_whitespace'] = True
6972

7073
indent_tabs = options.get('indent_tabs', False)
7174
if indent_tabs not in [True, False]:
72-
raise SQLParseError('Invalid value for indent_tabs: %r' % indent_tabs)
75+
raise SQLParseError('Invalid value for indent_tabs: '
76+
'{0!r}'.format(indent_tabs))
7377
elif indent_tabs:
7478
options['indent_char'] = '\t'
7579
else:

tests/test_grouping.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ def test_comparison_with_functions(): # issue230
373373

374374
@pytest.mark.parametrize('start', ['FOR', 'FOREACH'])
375375
def test_forloops(start):
376-
p = sqlparse.parse('%s foo in bar LOOP foobar END LOOP' % start)[0]
376+
p = sqlparse.parse('{0} foo in bar LOOP foobar END LOOP'.format(start))[0]
377377
assert (len(p.tokens)) == 1
378378
assert isinstance(p.tokens[0], sql.For)
379379

tests/test_regressions.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,11 @@ def test_comment_encoding_when_reindent():
171171

172172
def test_parse_sql_with_binary():
173173
# See https://github.com/andialbrecht/sqlparse/pull/88
174+
# digest = '‚|ËêŠplL4¡h‘øN{'
174175
digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{'
175-
sql = 'select * from foo where bar = \'%s\'' % digest
176+
sql = "select * from foo where bar = '{0}'".format(digest)
176177
formatted = sqlparse.format(sql, reindent=True)
177-
tformatted = 'select *\nfrom foo\nwhere bar = \'%s\'' % digest
178+
tformatted = "select *\nfrom foo\nwhere bar = '{0}'".format(digest)
178179
if sys.version_info < (3,):
179180
tformatted = tformatted.decode('unicode-escape')
180181
assert formatted == tformatted
@@ -193,10 +194,8 @@ def test_dont_alias_keywords():
193194
def test_format_accepts_encoding(): # issue20
194195
sql = load_file('test_cp1251.sql', 'cp1251')
195196
formatted = sqlparse.format(sql, reindent=True, encoding='cp1251')
196-
if sys.version_info < (3,):
197-
tformatted = u'insert into foo\nvalues (1); -- Песня про надежду\n'
198-
else:
199-
tformatted = 'insert into foo\nvalues (1); -- Песня про надежду\n'
197+
tformatted = u'insert into foo\nvalues (1); -- Песня про надежду\n'
198+
200199
assert formatted == tformatted
201200

202201

@@ -278,10 +277,7 @@ def test_issue186_get_type():
278277

279278

280279
def test_issue212_py2unicode():
281-
if sys.version_info < (3,):
282-
t1 = sql.Token(T.String, u"schöner ")
283-
else:
284-
t1 = sql.Token(T.String, "schöner ")
280+
t1 = sql.Token(T.String, u"schöner ")
285281
t2 = sql.Token(T.String, u"bug")
286282
l = sql.TokenList([t1, t2])
287283
assert str(l) == 'schöner bug'

tests/test_tokenize.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def test_error(self):
151151
'CROSS JOIN', 'STRAIGHT JOIN',
152152
'INNER JOIN', 'LEFT INNER JOIN'])
153153
def test_parse_join(expr):
154-
p = sqlparse.parse('%s foo' % expr)[0]
154+
p = sqlparse.parse('{0} foo'.format(expr))[0]
155155
assert len(p.tokens) == 3
156156
assert p.tokens[0].ttype is T.Keyword
157157

0 commit comments

Comments
 (0)