Skip to content

Commit 93e5634

Browse files
committed
Fixes RustPython#328, add object.__format__
1 parent d8afc6a commit 93e5634

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

tests/snippets/builtin_format.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,12 @@
66
pass
77
else:
88
assert False, "TypeError not raised when format is called with a number"
9+
10+
assert format({}) == "{}"
11+
12+
try:
13+
format({}, 'b')
14+
except TypeError:
15+
pass
16+
else:
17+
assert False, "TypeError not raised when format_spec not empty for dict"

vm/src/obj/objobject.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,15 @@ fn object_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
8484
Ok(vm.new_str(format!("<{} object at 0x{:x}>", type_name, address)))
8585
}
8686

87+
fn object_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
88+
arg_check!(vm, args, required = [(obj, Some(vm.ctx.object())), (format_spec, Some(vm.ctx.str_type()))]);
89+
if objstr::get_value(format_spec).is_empty() {
90+
vm.to_str(obj)
91+
} else {
92+
Err(vm.new_type_error("unsupported format string passed to object.__format__".to_string()))
93+
}
94+
}
95+
8796
pub fn init(context: &PyContext) {
8897
let object = &context.object;
8998
let object_doc = "The most base type";
@@ -101,6 +110,7 @@ pub fn init(context: &PyContext) {
101110
context.set_attr(&object, "__hash__", context.new_rustfunc(object_hash));
102111
context.set_attr(&object, "__str__", context.new_rustfunc(object_str));
103112
context.set_attr(&object, "__repr__", context.new_rustfunc(object_repr));
113+
context.set_attr(&object, "__format__", context.new_rustfunc(object_format));
104114
context.set_attr(
105115
&object,
106116
"__getattribute__",

0 commit comments

Comments
 (0)