[Python-ideas] without(str(bytes))
Ronald Oussoren
ronaldoussoren at mac.com
Thu Jun 6 11:48:31 CEST 2013
On 6 Jun, 2013, at 2:51, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Jun 5, 2013, at 10:53, Daniel Holth <dholth at gmail.com> wrote:
>
>> On Wed, Jun 5, 2013 at 1:10 PM, Brett Cannon <brett at python.org> wrote:
>>>
>>>
>>>
>>> On Wed, Jun 5, 2013 at 12:33 PM, Serhiy Storchaka <storchaka at gmail.com>
>>> wrote:
>>>>
>>>> 05.06.13 18:54, Daniel Holth написав(ла):
>>>>
>>>>> Can I have a context manager that disables str(bytes) just for part of
>>>>> my code, the same as python -bb?
>>>>>
>>>>> with bb:
>>>>> serialize_something()
>>>>
>>>>
>>>> No, you can't.
>>>>
>>>> But it looks as interesting idea. Perhaps it should be a function in the
>>>> sys module.
>>>>
>>>> with sys.alter_flags(bytes_warning=2, dont_write_bytecode=1):
>>>> ...
>>>
>>>
>>> Future statements affect the parser, so by the time the code is executed
>>> there's nothing you could affect. If you really want this sort of thing you
>>> can use compile() and it's flag argument.
>>
>> I don't know about the bytecodes, I was thinking more along the lines
>> of turning Py_BytesWarningFlag into a threadlocal and having the new
>> context manager modify that and the warning filter for
>> PyExc_BytesWarning.
>
> The problem is that the warning happens at compile time, but the context manager runs at runtime, at which point it's too late to do any good. You'd need some kind of compile-time context manager (and compile-time-with statement) to make that work.
I might be missing something, but wat Daniel proposes is a change in runtime behavior: the '-bb' flag affects the behavior of bytes.__str__ and not the generated bytecode (and the warning is emitted when bytes.__str__ is actually called, not during bytecode compilation). The contextmanager would set and reset 'Py_BytesWarningFlag'.
Ronald
More information about the Python-ideas
mailing list