8 Dec 21:07
Re: req - block-local variables
> On Sat, 2007-12-08 at 10:03 +0100, Stefan Behnel wrote:
> > David McNab wrote:
> > > I'm wishing for the ability to declare cdef vars within blocks
> > > whose scope is confined to the block, just like in C - no
> > > 'leaking out'.
> >
> > That would be mainly of syntactical interest. While I understand
> > that it would be nice for readability to declare a name only in
> > the scope where it is supposed to be used, you would likely not
> > gain much performance-wise, as C compilers are pretty good in
> > figuring out the 'real' scope of a variable.
Something that is allowed in all versions of C is declaring new
variables at the top of a block, which can then be used only in that
block. One could say: move the variable to the top of the function or
method, as we've stated in the rest of this e-mail thread.
But, there is a situation that can be (ab)used in C in which this
cannot be done without some thought: it's possible to declare
variables with the same name in different blocks that do not have the
same type. For example (in C):
if (something == 0)
{
unsigned int i;
for (i = 0; i < something_that_is_unsigned; i++)
do_something1();
}
else
{
int i;
for (i = 0; i < something_that_is_signed; i++)
do_something2();
}
This is a bad example, but you get the picture.
I can imagine a situation in Pyrex/Cython in which you would want to
use the same variable name (for clarity or readability) in different
blocks, but with different types. For example:
if isinstance(an_object, some_specific_list_type):
cdef item_in_the_list_type item
for item in an_object:
item.something_specific()
else:
cdef object item
for item in an_object:
something_generic(item)
> Agreed - the idea was only for readability, with no performance goal
> in mind.
But in the above example, it is possible that the code in the first
block is compiled to something faster because of the knowledge that
the items in the list are of some specific type (or perhaps, the
'something_specific' method is a C method that can only be called if
the 'item' is known to be of type 'item_in_the_list_type').
Of course, the programmer could simply declare two cdefs at the top of
the function called 'item1' and 'item2' or something similar.
I realize that in Python, it does not work this way (and in fact, the
type difference is not a issue in pure Python anyway), which would
make Pyrex/Cython less compatible with pure Python. Therefore, it
might not be a good idea to implement such a possibility.
> I find that with large functions, it's distracting to keep flipping
> between lines of code in the function and the cdef vars at the top
> of the function.
Certainly true.
> Cheers
> David
--
--
With kind regards,
Sven
RSS Feed