[Tutor] Why doesn't this filter FutureWarning?
Kent Johnson
kent_johnson at skillsoft.com
Tue Oct 19 13:55:43 CEST 2004
Wow, this one had me stumped for a while!
It turns out that this warning is generated at *compile* time, not at
runtime! Here is a way to demonstrate this:
In FW.py:
def foo():
num=0x1234
num=num & 0xffffffff
print 'foo'
In the interpreter:
>>> import FW
FW.py:3: FutureWarning: hex/oct constants > sys.maxint will return positive
values in Python 2.4 and up
num=num & 0xffffffff
>>> FW.foo()
foo
Notice I get the warning on import, even though all the code in FW is in a
function which is not executed! Then when I execute foo(), I *don't* get
the warning.
When you run from the command line, each line of input is compiled
independently. So setting the warning filter affects everything after.
When you run from a file, the whole file is compiled, generating the
warning, then the file is executed, disabling the warning. The warning
filter isn't set until after the file is compiled, so it is too late.
Two workarounds:
- Use 0xffffffffL and avoid the warning completely
- Put the call to filterwarnings() in a separate file. Call
filterwarnings(), then import the file of interest. You can simulate this
from the command line:
>>> import warnings
>>> warnings.filterwarnings(action='ignore', category=FutureWarning)
>>> import FW
>>> FW.foo()
foo
Kent
At 06:00 PM 10/17/2004 -0700, Terry Carroll wrote:
>Here's what I get in the interactive session:
>
> >>> num=0x1234
> >>> import warnings
> >>> num=num & 0xffffffff
><stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return
>positive va
>lues in Python 2.4 and up
> >>> warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning)
> >>> num=num & 0xffffffff
>
>
>That's just what I'd expect. I get the FutureWarning on the first try,
>but after invoking filterwarnings, I no longer get it.
>
>But when I do the same code from inside a file:
>
><begin quote>
>
>C:\test>cat fw.py
>num=0x1234
>import warnings
>num=num & 0xffffffff
>warnings.filterwarnings('ignore', "hex/oct constants", FutureWarning)
>num=num & 0xffffffff
>
>C:\test>python fw.py
>fw.py:3: FutureWarning: hex/oct constants > sys.maxint will return
>positive valu
>es in Python 2.4 and up
> num=num & 0xffffffff
>fw.py:5: FutureWarning: hex/oct constants > sys.maxint will return
>positive valu
>es in Python 2.4 and up
> num=num & 0xffffffff
>
><end-quote>
>
>What gives? Why would this work in an interactive session, but not from
>a file?
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list