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

[Lang] Fix string format not support keywords format #3256

Merged
merged 2 commits into from
Oct 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
ailzhang marked this conversation as resolved.
Show resolved Hide resolved
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()