473,795 Members | 2,830 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

slice notation as values?

Now slices are objects in python, I was wondering if slice
notation will be usable outside subscribtion in the future.

Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):

--
Antoon Pardon
Dec 9 '05 #1
23 2341
Antoon Pardon wrote:
Now slices are objects in python, I was wondering if slice
notation will be usable outside subscribtion in the future.

Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):

Do you mean

for key, value in tree.items()['alfa.': 'beta.']:

What would this mean?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 9 '05 #2
Op 2005-12-09, Steve Holden schreef <st***@holdenwe b.com>:
Antoon Pardon wrote:
Now slices are objects in python, I was wondering if slice
notation will be usable outside subscribtion in the future.

Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):

Do you mean

for key, value in tree.items()['alfa.': 'beta.']:


No, the slice is meant to be a parameter to the method.
It would be a more convenient way to write:

for key, value in tree.items(slic e('alfa.', 'beta.'))

--
Antoon Pardon
Dec 9 '05 #3
Antoon Pardon wrote:
Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):


The first of these works fine, except you need to use the correct syntax:
a = slice(4,9)
range(10)[a] [4, 5, 6, 7, 8]
The second also works fine, provide tree is a type which supports it and
you rewrite the call as tree.items(slic e('alfa','beta. ')) or perhaps
tree['alfa':'beta.'].items(). To support slicing directly on a dictionary
you could do:
class sliceable(dict) : def __getitem__(sel f, item):
if isinstance(item , slice):
return self.__class__( (k,v) for (k,v) in self.iteritems( )
if item.start <= k < item.stop)
return dict.__getitem_ _(self, item)
d = sliceable({'alp ha': 1, 'aaa': 2, 'beta': 3, 'bee': 4 })
d['alpha':'beta'] {'alpha': 1, 'bee': 4} d['alpha':'beta.'] {'alpha': 1, 'beta': 3, 'bee': 4} for key, value in d['alpha':'beta.'].items():

print key, value
alpha 1
beta 3
bee 4

It seems unlikely that this will make it into the builtin dict type, but
you never know.
Dec 9 '05 #4
Op 2005-12-09, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon wrote:
Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):


The first of these works fine, except you need to use the correct syntax:


Sure, I know that. But why a different syntax?

If we have lst = range(10), we can write

lst[slice(3,7)]

instead of

lst[3:7]

Now my impression is that should we only have the upper notation, slices
would be less usefull, because it would make using them more cumbersome.

I think that having this easy notation for slices available in more
general circumstances, would make the use of them in other situations
more easy too.
a = slice(4,9)
range(10)[a] [4, 5, 6, 7, 8]
The second also works fine, provide tree is a type which supports it and
you rewrite the call as tree.items(slic e('alfa','beta. ')) or perhaps
tree['alfa':'beta.'].items(). To support slicing directly on a dictionary
you could do:

class sliceable(dict) : def __getitem__(sel f, item):
if isinstance(item , slice):
return self.__class__( (k,v) for (k,v) in self.iteritems( )
if item.start <= k < item.stop)
return dict.__getitem_ _(self, item)
d = sliceable({'alp ha': 1, 'aaa': 2, 'beta': 3, 'bee': 4 })
d['alpha':'beta'] {'alpha': 1, 'bee': 4} d['alpha':'beta.'] {'alpha': 1, 'beta': 3, 'bee': 4} for key, value in d['alpha':'beta.'].items():

print key, value

alpha 1
beta 3
bee 4

It seems unlikely that this will make it into the builtin dict type, but
you never know.


It doesn't need to be in the buildin dict type, I just would think it
could make the interface to my own treedict type more intuitive.

In my treedict the keys are accessible in order. If you have dictionary
with strings as keys doing:

for key in tree:

will give you the keys in alfabetical order. Doing

for key in tree['a':'b']:

will give you all the keys that start with an 'a'.

Now there are a number of methods with similar results.
keys, values, items and there iter variants iterkeys,
itervalues and iteritems. These methods are 'sliceable'
too and I think the possibilty of giving such a method
a slice as parameter, with the same notation as in
a subscript, would be the clearest way for the user
to provide slice information.

If the user can write:

for key in tree['a':'b']:

Why shouldn't he be able to write:

for key, value in tree.iteritems( 'a':'b'):

--
Antoon Pardon
Dec 9 '05 #5
Antoon Pardon asked:

If we have lst = range(10), we can write

lst[slice(3,7)]

instead of

lst[3:7]

Now my impression is that should we only have the upper notation, slices
would be less usefull, because it would make using them more cumbersome.
Quite right, but the syntax for the slice only applies inside the square
brackets and there would be big problems making it work outside a
subscript. If you allowed a:b you get syntactic ambiguities: e.g. is this a
slice or a complete if statement:

if a:b

If you allow a slice on its own but require the square brackets still to be
there then you don't (I think) get any syntax ambiguities, but the result
looks like it should be some weird list comprehension so its just too
confusing:

myslice = [a:b]

I think the case for freestanding slices is there, but they aren't common
enough to justify special syntax.
If the user can write:

for key in tree['a':'b']:

Why shouldn't he be able to write:

for key, value in tree.iteritems( 'a':'b'):

import this

....
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
....

If the user can write

for key in tree['a':'b']:

then he can write:

for key in tree['a':'b'].iteritems():

so why add a second way to do that?
Dec 9 '05 #6
Op 2005-12-09, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon asked:

If we have lst = range(10), we can write

lst[slice(3,7)]

instead of

lst[3:7]

Now my impression is that should we only have the upper notation, slices
would be less usefull, because it would make using them more cumbersome.
Quite right, but the syntax for the slice only applies inside the square
brackets and there would be big problems making it work outside a
subscript. If you allowed a:b you get syntactic ambiguities: e.g. is this a
slice or a complete if statement:

if a:b

If you allow a slice on its own but require the square brackets still to be
there then you don't (I think) get any syntax ambiguities, but the result
looks like it should be some weird list comprehension so its just too
confusing:

myslice = [a:b]


I don't see the problem. The syntax for tuples can create syntactic
ambiguities too. Take the following statement:

f(a,b)

Does the call have two parameters or one that is a tuple? In practice
one uses parenthesis to disambigue the stament. So in the above case
it would be a complete if statement. And myslice = a:b wouldn't
cause a problem.
I think the case for freestanding slices is there, but they aren't common
enough to justify special syntax.
If the user can write:

for key in tree['a':'b']:

Why shouldn't he be able to write:

for key, value in tree.iteritems( 'a':'b'):

import this

...
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
...

If the user can write

for key in tree['a':'b']:

then he can write:

for key in tree['a':'b'].iteritems():


No he can't. tree['a':'b'] would provide a list
of keys that all start with an 'a'. Such a list
doesn't have an iteritems method. It wouldn't even
contain the information to construct items.

--
Antoon Pardon
Dec 9 '05 #7
Antoon Pardon wrote:
If the user can write

for key in tree['a':'b']:

then he can write:

for key in tree['a':'b'].iteritems():


No he can't. tree['a':'b'] would provide a list
of keys that all start with an 'a'. Such a list
doesn't have an iteritems method. It wouldn't even
contain the information to construct items.


Why would it produce a list?

Slicing a *list* produces a list, slicing a tuple produces a tuple, slicing
a string produces a string. I would expect slicing any other type would
also return you a new object of the same type. Thats what the code sample I
posted earlier does.
Dec 9 '05 #8
On 2005-12-09, Duncan Booth <du**********@i nvalid.invalid> wrote:
Antoon Pardon wrote:
If the user can write

for key in tree['a':'b']:

then he can write:

for key in tree['a':'b'].iteritems():
No he can't. tree['a':'b'] would provide a list
of keys that all start with an 'a'. Such a list
doesn't have an iteritems method. It wouldn't even
contain the information to construct items.


Why would it produce a list?


Correction, it produces an iterator.
Slicing a *list* produces a list, slicing a tuple produces a tuple, slicing
a string produces a string. I would expect slicing any other type would
also return you a new object of the same type.


But iterating over a list, tuple or string, give you the elements
of a list, tuple or string one by one. Iterating over a dict
doesn't give you the elements one by one, but only the keys.

In general I use slices over a tree because I only want to iterate
over a specific subdomain of the keys. I'm not iterested in make
a tree over the subdomain. Making such a subtree would be an
enormous waste of resources.

So even if we agree that tree['a':'b'] should create a subtree.
Then I still would want a way to iterate over a subdomain of
the keys in the tree without creating a subtree. Yes this
would create more than one way to do the same thing. But
this is already so with builtin dicts where a number of methods
give you different ways to do things, apparantly because
according to circumstances one is more efficient than the other.

So lets agree that tree['a':'b'] would produce a subtree. Then
I still would prefer the possibility to do something like:

for key in tree.iterkeys(' a':'b')

Instead of having to write

for key in tree['a':'b'].iterkeys()

Sure I can now do it like this:

for key in tree.iterkeys(' a','b')

But the way default arguments work, prevents you from having
this work in an analague way as a slice.

With slice notation you could have the following two cases:

for key in tree.iterkeys(' a':)

for key in tree.iterkeys(: 'b')

But you can't do

for key in tree.iterkeys(' a',)

or more regrettably, you can't do:

for key in tree.iterkeys(, 'b')
I also think that other functions could benefit. For instance suppose
you want to iterate over every second element in a list. Sure you
can use an extended slice or use some kind of while. But why not extend
enumerate to include an optional slice parameter, so you could do it as
follows:

for el in enumerate(lst,: :2)

If you have an iterable, you sometime want to iterate over only a part
of it. The only way now to do so seems to be to either use a while
loop or create a second iterable over your limited domain and iterate
over the subiterable. I think it would be a an improvement if an
iterator could be constructed to just go over the subdomain within
your iterable. I also think that the most natural way to define
that subdomain would be by using slice notation.

--
Antoon Pardon
Dec 10 '05 #9
Antoon Pardon wrote:
So lets agree that tree['a':'b'] would produce a subtree. Then
I still would prefer the possibility to do something like:

for key in tree.iterkeys(' a':'b')

Instead of having to write

for key in tree['a':'b'].iterkeys()

Sure I can now do it like this:

for key in tree.iterkeys(' a','b')

But the way default arguments work, prevents you from having
this work in an analague way as a slice.


How so? Can't you just pass the *args to the slice contstructor? E.g.::

def iterkeys(self, *args):
keyslice = slice(*args)
...

Then you can use the slice object just as you would have otherwise.

STeVe
Dec 10 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2494
by: Roberto A. F. De Almeida | last post by:
I found that when using negative indices, the slice object passed to __getitem__ depends on the number of slices. An example to clarify: class a: def __getitem__(self, index): return index >>> b = a() >>> print b Traceback (most recent call last):
3
2359
by: Thomas Covello | last post by:
Why does the following code give this error: >>> TypeError: sequence index must be integer
4
2936
by: F. Da Costa | last post by:
Hi, I was wondering whether someone could enlighten me as to the reason why the slice does not work in IE when the arr is passed in properly. Checked the values in the srcArr and they are correct so no problems there. Gecko works as expected. Prior to entering the function I can slice the array being entered so I wouldn't expect an "Unexpected call to method or property access" (in IE 6). I guess its something silly but as of yet i'm...
108
6468
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
40
2619
by: Ron Adam | last post by:
After considering several alternatives and trying out a few ideas with a modified list object Bengt Richter posted, (Thank You), I think I've found a way to make slice operation (especially far end indexing) symmetrical and more consistent. So to find out if this is indeed a possibility, it would be nice to get a few opinions at this point. So blast away... or hopefully tell me what you like about it instead. ;-) (Any suggestions or...
19
2911
by: George Sakkis | last post by:
It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) would be equivalent to x = sorted(x)
2
7253
by: smichr | last post by:
It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that...
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10443
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10216
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7543
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.