Skip to content
Permalink
Browse files

upgraded to mostly f-strings (#1614)

  • Loading branch information
wschwab authored and fubuloubu committed Sep 23, 2019
1 parent efdc6e2 commit a3aaadb38ce2f1304efdd4688100906de64661f9
Showing with 329 additions and 414 deletions.
  1. +8 −14 scripts/fixed_address_creator.py
  2. +2 −2 tests/base_conftest.py
  3. +6 −6 tests/cli/vyper_compile/test_import_paths.py
  4. +3 −3 tests/compiler/test_pre_parser.py
  5. +2 −4 tests/conftest.py
  6. +1 −1 tests/parser/functions/test_raw_call.py
  7. +3 −3 tests/parser/types/numbers/test_constants.py
  8. +4 −4 tests/parser/types/test_bytes_literal.py
  9. +9 −21 tests/test_utils.py
  10. +1 −1 vyper/cli/vyper_compile.py
  11. +1 −1 vyper/cli/vyper_json.py
  12. +1 −1 vyper/cli/vyper_lll.py
  13. +3 −3 vyper/cli/vyper_serve.py
  14. +4 −4 vyper/compile_lll.py
  15. +12 −14 vyper/functions/functions.py
  16. +20 −14 vyper/functions/signatures.py
  17. +1 −1 vyper/parser/arg_clamps.py
  18. +3 −5 vyper/parser/constants.py
  19. +2 −2 vyper/parser/context.py
  20. +5 −5 vyper/parser/events.py
  21. +39 −38 vyper/parser/expr.py
  22. +5 −8 vyper/parser/external_call.py
  23. +3 −3 vyper/parser/function_definitions/parse_private_function.py
  24. +1 −1 vyper/parser/function_definitions/parse_public_function.py
  25. +3 −3 vyper/parser/function_definitions/utils.py
  26. +19 −23 vyper/parser/global_context.py
  27. +1 −1 vyper/parser/keccak256_helper.py
  28. +20 −20 vyper/parser/lll_node.py
  29. +6 −9 vyper/parser/parser.py
  30. +31 −41 vyper/parser/parser_utils.py
  31. +6 −9 vyper/parser/self_call.py
  32. +39 −69 vyper/parser/stmt.py
  33. +1 −1 vyper/signatures/event_signature.py
  34. +6 −6 vyper/signatures/function_signature.py
  35. +16 −27 vyper/signatures/interface.py
  36. +20 −22 vyper/types/convert.py
  37. +11 −13 vyper/types/types.py
  38. +11 −11 vyper/utils.py
@@ -78,10 +78,10 @@ def encode_vals(vals):
- t.s.head_state.receipts[-2].gas_used \
- t.s.last_tx.intrinsic_gas_used

print("500 bytes increment: %d" % (g2 - g1))
print("500 bytes increment: %d" % (g4 - g3))
print("25 items increment: %d" % (g3 - g1))
print("25 items increment: %d" % (g4 - g2))
print(f"500 bytes increment: {(g2 - g1)}")
print(f"500 bytes increment: {(g4 - g3)}")
print(f"25 items increment: {(g3 - g1)}")
print(f"25 items increment: {(g4 - g2)}")

# Create transaction
t = transactions.Transaction(0, 30 * 10**9, 2999999, '', 0, rlp_decoder_bytes)
@@ -92,13 +92,7 @@ def encode_vals(vals):

print("RLP decoder")
print("Instructions for launching:")
print('First send {} wei to {}'.format(
t.startgas * t.gasprice,
utils.checksum_encode(t.sender),
))
print('Publish this tx to create the contract: 0x{}'.format(
utils.encode_hex(rlp.encode(t)),
))
print('This is the contract address: {}'.format(
utils.checksum_encode(utils.mk_contract_address(t.sender, 0)),
))
print(f'First send {t.startgas * t.gasprice} wei to {utils.checksum_encode(t.sender)}')
print(f'Publish this tx to create the contract: 0x{utils.encode_hex(rlp.encode(t))}')
print('This is the contract address: '
f'{utils.checksum_encode(utils.mk_contract_address(t.sender, 0))}')
@@ -47,9 +47,9 @@ def __prepared_function(self, *args, **kwargs):
modifier, modifier_dict = kwargs.popitem()
if modifier not in self.ALLOWED_MODIFIERS:
raise TypeError(
"The only allowed keyword arguments are: %s" % self.ALLOWED_MODIFIERS)
f"The only allowed keyword arguments are: {self.ALLOWED_MODIFIERS}")
else:
raise TypeError("Use up to one keyword argument, one of: %s" % self.ALLOWED_MODIFIERS)
raise TypeError(f"Use up to one keyword argument, one of: {self.ALLOWED_MODIFIERS}")
return getattr(self._function(*args), modifier)(modifier_dict)


@@ -121,8 +121,8 @@ def test_import_parent_folder(tmp_path, assert_compile_failed):
@pytest.mark.parametrize('import_stmt', META_IMPORT_STMT)
def test_import_self_interface(import_stmt, tmp_path):
# a contract can access it's derived interface by importing itself
code = """
{}
code = f"""
{import_stmt}
@public
def know_thyself(a: address) -> uint256:
@@ -131,7 +131,7 @@ def know_thyself(a: address) -> uint256:
@public
def be_known() -> uint256:
return 42
""".format(import_stmt)
"""

tmp_path.joinpath('contracts').mkdir()

@@ -157,8 +157,8 @@ def be_known() -> uint256:
@pytest.mark.parametrize('import_stmt_foo', DERIVED_IMPORT_STMT_FOO)
def test_derived_interface_imports(import_stmt_baz, import_stmt_foo, tmp_path):
# contracts-as-interfaces should be able to contain import statements
baz_code = """
{}
baz_code = f"""
{import_stmt_baz}
@public
def foo(a: address) -> uint256:
@@ -167,7 +167,7 @@ def foo(a: address) -> uint256:
@public
def bar(_foo: address, _bar: address) -> uint256:
return Foo(_foo).bar(_bar)
""".format(import_stmt_baz)
"""

with tmp_path.joinpath('Foo.vy').open('w') as fp:
fp.write(FOO_CODE.format(import_stmt_foo))
@@ -61,13 +61,13 @@ def foo(contract_address: address) -> int128:

def test_version_pragma(get_contract):
from vyper import __version__
code = """
# @version {}
code = f"""
# @version {__version__}
@public
def test():
pass
""".format(__version__)
"""
assert get_contract(code)


@@ -105,11 +105,9 @@ def check_gas_on_chain(w3, tester, code, func=None, res=None):
# Computed upper bound on the gas consumption should
# be greater than or equal to the amount of gas used
if gas_estimate < gas_actual:
raise Exception("Gas upper bound fail: bound %d actual %d" % (gas_estimate, gas_actual))
raise Exception(f"Gas upper bound fail: bound {gas_estimate} actual {gas_actual}")

print('Function name: {} - Gas estimate {}, Actual: {}'.format(
func, gas_estimate, gas_actual)
)
print(f'Function name: {func} - Gas estimate {gas_estimate}, Actual: {gas_actual}')


def gas_estimation_decorator(w3, tester, fn, source_code, func):
@@ -64,7 +64,7 @@ def create_and_return_forwarder(inp: address) -> address:

print('Passed forwarder test')
# TODO: This one is special
# print('Gas consumed: %d' % (chain.head_state.receipts[-1].gas_used - chain.head_state.receipts[-2].gas_used - chain.last_tx.intrinsic_gas_used)) # noqa: E501
# print(f'Gas consumed: {(chain.head_state.receipts[-1].gas_used - chain.head_state.receipts[-2].gas_used - chain.last_tx.intrinsic_gas_used)}') # noqa: E501


def test_multiple_levels2(assert_tx_failed, get_contract_with_gas_estimation):
@@ -163,15 +163,15 @@ def is_owner() -> bool:

def test_constant_bytes(get_contract):
test_str = b"Alabama, Arkansas. I do love my ma and pa"
code = """
X: constant(bytes[100]) = b"{}"
code = f"""
X: constant(bytes[100]) = b"{test_str.decode()}"
@public
def test() -> bytes[100]:
y: bytes[100] = X
return y
""".format(test_str.decode())
"""

c = get_contract(code)

@@ -45,15 +45,15 @@ def test_bytes_literal_splicing_fuzz(get_contract_with_gas_estimation):
@public
def foo(s: int128, L: int128) -> bytes[100]:
x: int128 = 27
r: bytes[100] = slice(b"%s", start=s, len=L)
r: bytes[100] = slice(b"{0}", start=s, len=L)
y: int128 = 37
if x * y == 999:
return r
return b"3434346667777"
@public
def bar(s: int128, L: int128) -> bytes[100]:
self.moo = b"%s"
self.moo = b"{0}"
x: int128 = 27
r: bytes[100] = slice(self.moo, start=s, len=L)
y: int128 = 37
@@ -64,12 +64,12 @@ def bar(s: int128, L: int128) -> bytes[100]:
@public
def baz(s: int128, L: int128) -> bytes[100]:
x: int128 = 27
self.moo = slice(b"%s", start=s, len=L)
self.moo = slice(b"{0}", start=s, len=L)
y: int128 = 37
if x * y == 999:
return self.moo
return b"3434346667777"
""" % (("c" * i), ("c" * i), ("c" * i))
""".format(("c" * i))

c = get_contract_with_gas_estimation(kode)
for e in range(63, 64, 65):
@@ -75,22 +75,14 @@ def __str__(self):
if self.lineno and hasattr(self, 'source_code'):
output = 'line %d: %s\n%s' % (
self.lineno,
output,
self.source_code[self.lineno - 1]
)
output = f'line {self.lineno}: {output}\n{self.source_code[self.lineno -1]}'
if self.col_offset:
col = '-' * self.col_offset + '^'
output += '\n' + col
elif self.lineno is not None and self.col_offset is not None:
output = 'line %d:%d %s' % (
self.lineno,
self.col_offset,
output
)
output = f'line {self.lineno}:{self.col_offset} {output}'
return output
"""[1:-1]
@@ -156,21 +148,17 @@ def __str__(self):

annotation = annotate_source_code(
TEST_SOURCE_CODE,
44,
36,
col_offset=8,
context_lines=8,
context_lines=4,
line_numbers=True,
)
assert annotation == r"""
36
37 elif self.lineno is not None and self.col_offset is not None:
38 output = 'line %d:%d %s' % (
39 self.lineno,
40 self.col_offset,
41 output
42 )
43
---> 44 return output
32
33 elif self.lineno is not None and self.col_offset is not None:
34 output = f'line {self.lineno}:{self.col_offset} {output}'
35
---> 36 return output
----------------^
"""[1:-1]

@@ -73,7 +73,7 @@ def _parse_args(argv):
parser.add_argument(
'--version',
action='version',
version='{0}+commit.{1}'.format(vyper.__version__, vyper.__commit__),
version=f'{vyper.__version__}+commit.{vyper.__commit__}',
)
parser.add_argument(
'--show-gas-estimates',
@@ -63,7 +63,7 @@ def _parse_args(argv):
parser.add_argument(
'--version',
action='version',
version='{0}+commit.{1}'.format(vyper.__version__, vyper.__commit__),
version=f'{vyper.__version__}+commit.{vyper.__commit__}',
)
parser.add_argument(
'-o',
@@ -28,7 +28,7 @@ def _parse_args(argv):
parser.add_argument(
'--version',
action='version',
version='{0}'.format(vyper.__version__),
version=f'{vyper.__version__}',
)
parser.add_argument(
'-f',
@@ -28,7 +28,7 @@ def _parse_args(argv):
parser = argparse.ArgumentParser(
description='Serve Vyper compiler as an HTTP Service'
)
parser.add_argument('--version', action='version', version='{0}'.format(vyper.__version__))
parser.add_argument('--version', action='version', version=f'{vyper.__version__}')
parser.add_argument(
'-b',
help='Address to bind JSON server on, default: localhost:8000',
@@ -66,7 +66,7 @@ def do_GET(self):
self.send_response(200)
self.send_cors_all()
self.end_headers()
self.wfile.write('Vyper Compiler. Version: {} \n'.format(vyper.__version__).encode())
self.wfile.write('Vyper Compiler. Version: ' + (vyper.__version__).encode() + '\n')
else:
self.send_404()

@@ -134,5 +134,5 @@ class VyperHTTPServer(ThreadingMixIn, HTTPServer):
def runserver(host='', port=8000):
server_address = (host, int(port))
httpd = VyperHTTPServer(server_address, VyperRequestHandler)
print('Listening on http://{0}:{1}'.format(host, port))
print(f'Listening on http://{host}:{port}')
httpd.serve_forever()
@@ -109,9 +109,9 @@ def compile_to_assembly(code, withargs=None, existing_labels=None, break_dest=No
# Numbers
elif isinstance(code.value, int):
if code.value <= -2**255:
raise Exception("Value too low: %d" % code.value)
raise Exception(f"Value too low: {code.value}")
elif code.value >= 2**256:
raise Exception("Value too high: %d" % code.value)
raise Exception(f"Value too high: {code.value}")
bytez = num_to_bytearray(code.value % 2**256) or [0]
return ['PUSH' + str(len(bytez))] + bytez
# Variables connected to with statements
@@ -298,7 +298,7 @@ def compile_to_assembly(code, withargs=None, existing_labels=None, break_dest=No
)
else:
raise Exception(
"Invalid %r with values %r and %r" % (code.value, code.args[0], code.args[1])
f"Invalid {code.value} with values {code.args[0]} and {code.args[1]}"
)
o = compile_to_assembly(code.args[0], withargs, existing_labels, break_dest, height)
o.extend(compile_to_assembly(
@@ -437,7 +437,7 @@ def compile_to_assembly(code, withargs=None, existing_labels=None, break_dest=No
label_name = str(code.args[0])

if label_name in existing_labels:
raise Exception('Label with name %s already exists!', label_name)
raise Exception(f'Label with name {label_name} already exists!')
else:
existing_labels.add(label_name)

0 comments on commit a3aaadb

Please sign in to comment.
You can’t perform that action at this time.