Skip to content

Simplified django.utils.functional.lazy(). - #11314

Closed
bluetech wants to merge 9 commits into
django:mainfrom
bluetech:lazywebz
Closed

bluetech wants to merge 9 commits into
django:mainfrom
bluetech:lazywebz

Conversation

@bluetech

@bluetech bluetech commented May 3, 2019 •

Copy link
Copy Markdown
Contributor

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.

@bluetech

bluetech commented May 3, 2019

Copy link
Copy Markdown
Contributor Author

The CI failure is unrelated: hudson.plugins.git.GitException: Failed to fetch from git://github.com/django/django.git.

@bluetech bluetech changed the title Simplified django.utils.functional.lazy() and fixed performance bug. Simplified django.utils.functional.lazy(). May 22, 2019
@bluetech
bluetech force-pushed the lazywebz branch 2 times, most recently from 14534cf to 202b586 Compare July 29, 2019 19:44
@bluetech

Copy link
Copy Markdown
Contributor Author

I rebased and removed a bad commit; the CI passed now.

@ngnpope ngnpope left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)()
False

After:

>>> from django.utils.functional import lazy
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, str)()
True
>>> lazy(lambda: 1, str)() == lazy(lambda: 1, bytes)()
True

Comment thread django/utils/functional.py Resolved
Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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...

Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread django/utils/functional.py Resolved
Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Am not sure that I follow the argument for this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to rephrase.

If _delegate_bytes is true, there are two possible situations:

  1. The result type of the function is bytes, that is func(*self.__args, **self.__kw) returns bytes. In this case, __bytes_cast just calls bytes() on a bytes instance, which is redundant.

  2. The result type of the function is not bytes. This is possible if the resultclasses is something like lazy(func, bytes, int) and the result of the function call is an int. In this case, the behavior before the commit was, that whenever the result is not a bytes, it is cast to bytes. I find that very unexpected, and I don't think it is intended behavior, but a bug. So this commit removes this behavior.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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__.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 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__.

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__']

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 bluetech left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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...

Comment thread django/utils/functional.py Resolved
Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to rephrase.

If _delegate_bytes is true, there are two possible situations:

  1. The result type of the function is bytes, that is func(*self.__args, **self.__kw) returns bytes. In this case, __bytes_cast just calls bytes() on a bytes instance, which is redundant.

  2. The result type of the function is not bytes. This is possible if the resultclasses is something like lazy(func, bytes, int) and the result of the function call is an int. In this case, the behavior before the commit was, that whenever the result is not a bytes, it is cast to bytes. I find that very unexpected, and I don't think it is intended behavior, but a bug. So this commit removes this behavior.

Comment thread django/utils/functional.py Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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__.

@bluetech

Copy link
Copy Markdown
Contributor Author

Based on my comments, are we sure that there isn't some untested case that has changed?

In your example lazy(lambda: 1, str)(), the function returns an int but the specified resultclass is str. This I believe is already "illegal" and breaks the contract of lazy and will cause super-confusing issues to anyone who does this by mistake. So I think it's OK.

@ngnpope

ngnpope commented Jul 31, 2019

Copy link
Copy Markdown
Member

In your example lazy(lambda: 1, str)(), the function returns an int but the specified resultclass is str. This I believe is already "illegal" and breaks the contract of lazy and will cause super-confusing issues to anyone who does this by mistake. So I think it's OK.

Yeah, that was a sloppy example, but it "worked" before. I fear that we are now claiming str and bytes to be equivalent which definitely feels like a regression.

It seems ill-defined what makes sense here. The (now-removed) code that asserts that bytes and str are incompatible. The undocumented invalid combinations, e.g. str and int. The apparently valid str, tuple and list for get_format_lazy().

Maybe all the complexity is just a hang over from the old Python 2 days of str vs unicode and not all that has been removed.

@bluetech

bluetech commented Aug 1, 2019

Copy link
Copy Markdown
Contributor Author

Yeah, that was a sloppy example, but it "worked" before.

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 fear that we are now claiming str and bytes to be equivalent which definitely feels like a regression.

I don't quite follow, can you clarify what you mean by equivalent?

Maybe all the complexity is just a hang over from the old Python 2 days of str vs unicode and not all that has been removed.

That's my understanding, that the _delegate_bytes and _delegate_str is only Python2 compat legacy. Why should str and bytes be special otherwise?

Comment thread django/utils/functional.py Resolved
Comment thread django/utils/functional.py Resolved
@bluetech

Copy link
Copy Markdown
Contributor Author

I couldn't resist adding another commit, "Changed proxy to prepare eagerly." (the commit message explains).

@bluetech
bluetech force-pushed the lazywebz branch 2 times, most recently from b15bdb9 to 426303f Compare April 27, 2020 08:46
Base automatically changed from master to main March 9, 2021 06:21

@auvipy auvipy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please fix the conflict please?

@bluetech
bluetech force-pushed the lazywebz branch 3 times, most recently from a39276e to 9b46aad Compare September 19, 2021 16:36
@bluetech

Copy link
Copy Markdown
Contributor Author

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 str and bytes in resultclasses is now allowed.

@felixxm

felixxm commented Mar 30, 2023

Copy link
Copy Markdown
Member

Merged the first two commits in 0a132de and 066aabc.

@nessita

nessita commented Apr 19, 2023

Copy link
Copy Markdown
Contributor

@bluetech Hi! I'm doing some PR cleanup, would you have time to update this PR with the latest main? Thank you!

@felixxm

felixxm commented Apr 19, 2023

Copy link
Copy Markdown
Member

@bluetech Let me know if you don't have time to keep working on this, I'm eager to move it forward.

@felixxm felixxm self-assigned this Apr 19, 2023
@ngnpope

ngnpope commented Apr 19, 2023

Copy link
Copy Markdown
Member

I might be able to pick this up. Have a few ideas for further improvements.

@bluetech

Copy link
Copy Markdown
Contributor Author

@felixxm @ngnpope Would be happy if you pick this up. It will take me some effort to page these changes in. But I can do the rebase if that would help - let me know.

I am quite sure it doesn't do anything different since
c716fe8 and
7b2f2e7.
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.
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}
@felixxm

felixxm commented Apr 20, 2023

Copy link
Copy Markdown
Member

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.
@ngnpope

ngnpope commented Jun 7, 2023

Copy link
Copy Markdown
Member

Superseded by #16954.

@ngnpope ngnpope closed this Jun 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants