Repository navigation
Conversation
|
The CI failure is unrelated: |
14534cf to
202b586
Compare
|
I rebased and removed a bad commit; the CI passed now. |
ngnpope
left a comment
There was a problem hiding this comment.
Based on my comments, are we sure that there isn't some untested case that has changed?
In fact, here is an example.
Before:
>>> from django.utils.functional import lazy
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, str)()
True
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, bytes)()
FalseAfter:
>>> from django.utils.functional import lazy
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, str)()
True
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, bytes)()
TrueThere was a problem hiding this comment.
This will be slightly different contrary to what is stated in your commit message.
Here it was overriding __str__ with cls.__text_cast which is effectively func(*self.__args, **self.__kw). After your change it'll be relying on the original __str__ which resolves to str(func(*self.__args, **self.__kw)).
Perhaps this isn't a problem after the following commits though - I'll continue reviewing, but this is noted here.
There was a problem hiding this comment.
That's true. But I think it ends up being the same. Consider that the code before the change does cls.__str__ = cls.__text_cast i.e. the assumption is that __text_cast() results in an str. As you say, the new code does the equivalent of str(__text_cast()), but str() on an str just returns the input, so that extra str shouldn't matter.
Now there may be some edge cases where what I said doesn't hold, like subclasses of str and whatnot. But the existing code is already broken by various edge cases, e.g.
>>> identity = lazy(lambda x: x, int, str)
>>> str(identity(1))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __str__ returned non-string (type int)I think that removing weird conditions will make it at least a little easier to reason about...
There was a problem hiding this comment.
So, after my previous comment, I think that this is not quite right. Perhaps func(*self.__args, **self.__kw) in __cast should be wrapped with str() which would really make __cast like __text_cast?
There was a problem hiding this comment.
Here I am making the same assumption I mentioned in the previous commit (which the current code makes already), that if __delegate_text is true, then __cast() would return an str. Hence this additional str is unnecessary.
There was a problem hiding this comment.
Am not sure that I follow the argument for this.
There was a problem hiding this comment.
I'll try to rephrase.
If _delegate_bytes is true, there are two possible situations:
-
The result type of the function is
bytes, that isfunc(*self.__args, **self.__kw)returnsbytes. In this case,__bytes_castjust callsbytes()on abytesinstance, which is redundant. -
The result type of the function is not
bytes. This is possible if the resultclasses is something likelazy(func, bytes, int)and the result of the function call is anint. In this case, the behavior before the commit was, that whenever the result is not abytes, it is cast tobytes. I find that very unexpected, and I don't think it is intended behavior, but a bug. So this commit removes this behavior.
There was a problem hiding this comment.
Ok.
So I had a look and only found the following cases of multiple resultclasses being defined:
django/template/backends/utils.py:csrf_input_lazy = lazy(csrf_input, SafeString, str)
django/utils/formats.py:get_format_lazy = lazy(get_format, str, list, tuple)In this case they are either compatible types or the expected supported types, e.g. for %-formatting.
There was a problem hiding this comment.
django/template/backends/utils.py:csrf_input_lazy = lazy(csrf_input, SafeString, str)
This is an interesting case. I checked and it seems to work as expected (new code):
>>> from django.utils.functional import lazy
>>> from django.utils.safestring import SafeString
>>> lazy_id = lazy(lambda x: x, SafeString, str)
>>> type(str(lazy_id("str")))
<class 'str'>
>>> type(str(lazy_id(SafeString("safe"))))
<class 'django.utils.safestring.SafeString'>django/utils/formats.py:get_format_lazy = lazy(get_format, str, list, tuple)
Before this PR, there was this bug:
>>> str(DateField.input_formats)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __str__ returned non-string (type list)After, it works fine.
There was a problem hiding this comment.
So now we have __proxy__.__str__ defined as str(self.__cast())...
...but __proxy__.__str__ is not defined at all. Maybe it should be bytes(self.__cast()).
There was a problem hiding this comment.
Did you mean to write __proxy__.__bytes__ instead of __proxy__.__str__ in the second sentence?
If so, the difference between __str__ and __bytes__ relates to the code comment inside def __str__ below; namely, that the object type defines __str__, but doesn't define __bytes__, so the special treatment that __str__ gets isn't needed for __bytes__.
There was a problem hiding this comment.
Did you mean to write
__proxy__.__bytes__instead of__proxy__.__str__in the second sentence?
Yes, sorry.
If so, the difference between
__str__and__bytes__relates to the code comment insidedef __str__below; namely, that theobjecttype defines__str__, but doesn't define__bytes__, so the special treatment that__str__gets isn't needed for__bytes__.
Ok. I see. I also notice that there a bunch of other things defined on __proxy__ that override those on object.
I wonder if there are any others here that ought to be that are not?
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
There was a problem hiding this comment.
From that list, I think the following might be considered:
__delattr__,__setattr__,__getattribute__: not sure, might be tricky?__reduce_ex__: not sure what this is, but we already forward__reduce__, so probably should forward this one too?__format__: should forward this, example:
>>> class CustomFormat:
... def __format__(self, format_spec):
... return 'custom'
...
>>> format(CustomFormat(), 'x')
'custom'
>>> format(lazy(lambda: CustomFormat(), CustomFormat)(), 'x')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: unsupported format string passed to __proxy__.__format__
bluetech
left a comment
There was a problem hiding this comment.
Thanks for review @pope1ni! These changes are quite tricky to follow...
I replied to all of the comments. Regarding the elif -> if fix, I'm afraid that if I push-force now it will jumble all of the comments on GitHub, so I'm holding it locally for now until the review is finished.
There was a problem hiding this comment.
That's true. But I think it ends up being the same. Consider that the code before the change does cls.__str__ = cls.__text_cast i.e. the assumption is that __text_cast() results in an str. As you say, the new code does the equivalent of str(__text_cast()), but str() on an str just returns the input, so that extra str shouldn't matter.
Now there may be some edge cases where what I said doesn't hold, like subclasses of str and whatnot. But the existing code is already broken by various edge cases, e.g.
>>> identity = lazy(lambda x: x, int, str)
>>> str(identity(1))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __str__ returned non-string (type int)I think that removing weird conditions will make it at least a little easier to reason about...
There was a problem hiding this comment.
Here I am making the same assumption I mentioned in the previous commit (which the current code makes already), that if __delegate_text is true, then __cast() would return an str. Hence this additional str is unnecessary.
There was a problem hiding this comment.
I'll try to rephrase.
If _delegate_bytes is true, there are two possible situations:
-
The result type of the function is
bytes, that isfunc(*self.__args, **self.__kw)returnsbytes. In this case,__bytes_castjust callsbytes()on abytesinstance, which is redundant. -
The result type of the function is not
bytes. This is possible if the resultclasses is something likelazy(func, bytes, int)and the result of the function call is anint. In this case, the behavior before the commit was, that whenever the result is not abytes, it is cast tobytes. I find that very unexpected, and I don't think it is intended behavior, but a bug. So this commit removes this behavior.
There was a problem hiding this comment.
Did you mean to write __proxy__.__bytes__ instead of __proxy__.__str__ in the second sentence?
If so, the difference between __str__ and __bytes__ relates to the code comment inside def __str__ below; namely, that the object type defines __str__, but doesn't define __bytes__, so the special treatment that __str__ gets isn't needed for __bytes__.
In your example |
Yeah, that was a sloppy example, but it "worked" before. I fear that we are now claiming It seems ill-defined what makes sense here. The (now-removed) code that asserts that Maybe all the complexity is just a hang over from the old Python 2 days of |
I don't think bug-compatibility should be kept here, especially since making this mistake is very visible so it's unlikely that some code has this bug and is working correctly.
I don't quite follow, can you clarify what you mean by equivalent?
That's my understanding, that the |
|
I couldn't resist adding another commit, "Changed proxy to prepare eagerly." (the commit message explains). |
b15bdb9 to
426303f
Compare
auvipy
left a comment
There was a problem hiding this comment.
could you please fix the conflict please?
a39276e to
9b46aad
Compare
|
Rebased. The two conflicts were with 577f233 and 775b796 (cc @hramezani) which were not semantic conflicts, except for the test which is now passing because having both |
|
@bluetech Hi! I'm doing some PR cleanup, would you have time to update this PR with the latest main? Thank you! |
|
@bluetech Let me know if you don't have time to keep working on this, I'm eager to move it forward. |
|
I might be able to pick this up. Have a few ideas for further improvements. |
It is not used anymore.
If the result type is bytes, then calling bytes() on it does nothing. If the result type is not bytes, I don't see any reason why it should be cast to bytes, just because the return value *may* be bytes.
Similarly to the previous commit, this is not necessary.
No longer used.
They are not special cased anymore, so I don't see any particular reason for this check.
This order reads more naturally.
`@total_ordering` is slow. Implementing manually is not too ugly.
Using the following micro-benchmark (resultclasses intentionally omitted
to narrow the scope):
import cProfile
from django.utils.functional import lazy
def identity(x): return x
cProfile.run("for i in range(10000): str(lazy(identity)(1))")
Before:
380003 function calls in 0.304 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.016 0.016 0.304 0.304 <string>:1(<module>)
10000 0.002 0.000 0.002 0.000 bench.py:5(double)
10000 0.005 0.000 0.006 0.000 functional.py:100(__cast)
10000 0.007 0.000 0.013 0.000 functional.py:106(__str__)
10000 0.005 0.000 0.017 0.000 functional.py:140(__wrapper__)
10000 0.020 0.000 0.258 0.000 functional.py:60(lazy)
10000 0.039 0.000 0.039 0.000 functional.py:68(__proxy__)
10000 0.010 0.000 0.012 0.000 functional.py:77(__init__)
10000 0.002 0.000 0.002 0.000 functional.py:84(__prepare_class__)
10000 0.025 0.000 0.075 0.000 functools.py:186(total_ordering)
10000 0.015 0.000 0.028 0.000 functools.py:189(<setcomp>)
10000 0.024 0.000 0.044 0.000 functools.py:37(update_wrapper)
10000 0.005 0.000 0.005 0.000 functools.py:67(wraps)
10000 0.074 0.000 0.114 0.000 {built-in method builtins.__build_class__}
1 0.000 0.000 0.304 0.304 {built-in method builtins.exec}
150000 0.023 0.000 0.023 0.000 {built-in method builtins.getattr}
10000 0.004 0.000 0.004 0.000 {built-in method builtins.max}
80000 0.025 0.000 0.025 0.000 {built-in method builtins.setattr}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
10000 0.003 0.000 0.003 0.000 {method 'update' of 'dict' objects}
After:
240003 function calls in 0.231 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.016 0.016 0.231 0.231 <string>:1(<module>)
10000 0.002 0.000 0.002 0.000 bench.py:5(double)
10000 0.006 0.000 0.012 0.000 functional.py:105(__str__)
10000 0.005 0.000 0.017 0.000 functional.py:159(__wrapper__)
10000 0.015 0.000 0.186 0.000 functional.py:60(lazy)
10000 0.022 0.000 0.022 0.000 functional.py:68(__proxy__)
10000 0.010 0.000 0.012 0.000 functional.py:76(__init__)
10000 0.002 0.000 0.002 0.000 functional.py:83(__prepare_class__)
10000 0.004 0.000 0.006 0.000 functional.py:99(__cast)
10000 0.023 0.000 0.043 0.000 functools.py:37(update_wrapper)
10000 0.004 0.000 0.004 0.000 functools.py:67(wraps)
10000 0.102 0.000 0.124 0.000 {built-in method builtins.__build_class__}
1 0.000 0.000 0.231 0.231 {built-in method builtins.exec}
70000 0.011 0.000 0.011 0.000 {built-in method builtins.getattr}
50000 0.007 0.000 0.007 0.000 {built-in method builtins.setattr}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
10000 0.003 0.000 0.003 0.000 {method 'update' of 'dict' objects}
|
Rebased. |
Previously, the proxy class was prepared lazily (excuse the pun):
lazy_identity = lazy(identity, int)
lazy_identity(10) # <- prepared here
lazy_identity(10)
This has a slight advantage that if the lazy doesn't end up getting
used, the preparation work is skipped, however that's not very likely.
Besides this laziness, it is also inconsistent in that the methods which
are wrapped directly (__str__ etc.) are prepared already when __proxy__
is defined, and there is a weird half-initialized state.
Change it so that everything is prepared already on the first line of
the example above.
|
Superseded by #16954. |
I have split the changes into small commits with rationale in the commit message, to make it easier to review and drop undesirable changes if needed. Should probably be squashed before merging.
The last commit "Fixed wrong caching of class preparation." fixes a performance issue that affected us in production. It can be applied separately.Moved to a separate PR: #11399.