Commit d7d47656 authored by Rudi Chen's avatar Rudi Chen

Implement intern() builtin function.

parent 27e24f67
......@@ -958,6 +958,16 @@ Box* input(Box* prompt) {
throwCAPIException();
}
Box* intern(Box* str) {
if (!PyString_Check(str)) {
raiseExcHelper(TypeError, "must be string, not %s", getTypeName(str));
}
if (!PyString_CheckExact(str)) {
raiseExcHelper(TypeError, "can't intern subclass of string");
}
return PyString_InternFromString(PyString_AsString(str));
}
Box* builtinRound(Box* _number, Box* _ndigits) {
if (!isSubclass(_number->cls, float_cls))
raiseExcHelper(TypeError, "a float is required");
......@@ -1104,6 +1114,9 @@ void setupBuiltins() {
builtins_module->giveAttr("__import__", new BoxedBuiltinFunctionOrMethod(import_func, "__import__",
{ None, None, None, new BoxedInt(-1) }));
Box* intern_obj = new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)intern, UNKNOWN, 1), "intern");
builtins_module->giveAttr("intern", intern_obj);
enumerate_cls = BoxedHeapClass::create(type_cls, object_cls, &BoxedEnumerate::gcHandler, 0, 0,
sizeof(BoxedEnumerate), false, "enumerate");
enumerate_cls->giveAttr(
......
try:
print intern(123)
except TypeError:
print "caught expected TypeError"
print intern("abcd")
class StringSubclass(str):
pass
# CPython does not allow interning on subclasses of str
try:
print intern(StringSubclass())
except TypeError:
print "caught expected TypeError from subclassing"
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment