Skip to content

Commit

Permalink
[Lang] Fix string format not support keywords format (#3256)
Browse files Browse the repository at this point in the history
* fix: string format not support keywords format

* fix: format in test
  • Loading branch information
yihong0618 authored Oct 25, 2021
1 parent d08f33c commit fac2118
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 9 additions & 3 deletions python/taichi/lang/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,20 +701,26 @@ def fused_string(entries):


@taichi_scope
def ti_format(*args):
def ti_format(*args, **kwargs):
content = args[0]
mixed = args[1:]
new_mixed = []
new_mixed_kwargs = {}
args = []
for x in mixed:
if isinstance(x, ti.Expr):
new_mixed.append('{}')
args.append(x)
else:
new_mixed.append(x)

for k, v in kwargs.items():
if isinstance(v, ti.Expr):
new_mixed_kwargs[k] = '{}'
args.append(v)
else:
new_mixed_kwargs[k] = v
try:
content = content.format(*new_mixed)
content = content.format(*new_mixed, **new_mixed_kwargs)
except ValueError:
print('Number formatting is not supported with Taichi fields')
exit(1)
Expand Down
16 changes: 16 additions & 0 deletions tests/python/test_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,19 @@ def test_python_scope_print_field():
print(x)
print(y)
print(z)


@ti.test(arch=ti.cpu)
def test_print_string_format():
@ti.kernel
def func(k: ti.f32):
print(123)
print("{} abc".format(123))
print("{} {} {}".format(1, 2, 3))
print("{} {name} {value}".format(k, name=999, value=123))
name = 123.4
value = 456.7
print("{} {name} {value}".format(k, name=name, value=value))

func(233.3)
ti.sync()

0 comments on commit fac2118

Please sign in to comment.