[IronPython] Django, __unicode__, and #20366

Dino Viehland dinov at microsoft.com
Mon Feb 1 22:21:27 CET 2010


It always prefers __unicode__ over __str__.  We can't really only call 
__unicode__ when __str__ isn't there because __str__ is always there.

We could do a search based upon MRO and call the first one we find but
I don't think that'll change the behavior very much and it'll certainly
be more difficult to understand.

The actual code is added to StringOps.FastNew:

            if (x is string) {
                // check ascii
                return CheckAsciiString(context, (string)x);
            }

+            object value;
+            if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__unicode__", out value)) {
+                if (value is string || value is Extensible<string>) {
+                    return value;
+                }
+                throw PythonOps.TypeError("coercing to Unicode: exected string, got {0}", PythonTypeOps.GetName(value));
+            }
+
+            OldInstance oi = x as OldInstance;
+
+            if (oi != null && oi.TryGetBoundCustomMember(context, "__unicode__", out value)) {
+                value = context.LanguageContext.Call(context, value);
+                if (value is string || value is Extensible<string>) {
+                    return value;
+                }
+                throw PythonOps.TypeError("coercing to Unicode: exected string, got {0}", PythonTypeOps.GetName(value));
+            }

            // we don't invoke PythonOps.StringRepr here because we want to return the 
            // Extensible<string> directly back if that's what we received from __str__.
            value = PythonContext.InvokeUnaryOperator(context, UnaryOperators.String, x);
            if (value is string || value is Extensible<string>) {
                return value;
            }

> -----Original Message-----
> From: users-bounces at lists.ironpython.com [mailto:users-
> bounces at lists.ironpython.com] On Behalf Of Jeff Hardy
> Sent: Monday, February 01, 2010 1:16 PM
> To: Discussion of IronPython
> Subject: Re: [IronPython] Django, __unicode__, and #20366
> 
> On Mon, Feb 1, 2010 at 1:19 PM, Dino Viehland <dinov at microsoft.com> wrote:
> > My initial test job didn't include support for __unicode__ on old-style
> classes or have the fix for exceptions.  I'm sending it through again to make
> sure those two changes didn't break anything else.  But I'm inclined to say
> that this change is for the better.  Thoughts?
> 
> How does the implementation work? Does always it prefer __unicode__ to
> __str__, or does it only call __unicode__ if it is present and __str__
> is missing?
> 
> - Jeff
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com



More information about the Ironpython-users mailing list