473,231 Members | 1,695 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

Finding the type of indexing supported by an object?

Here are two functions.

def invert_dict_to_lists(dict):
lists = {}
for key in dict:
value = dict[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

def invert_list_to_lists(list):
lists = {}
for key in range(len(list)):
value = list[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

They are the same except for the expression in "for key in ...". Can they
be combined into one function? How can I determine if the argument is
like a list (with numeric indices that are not stored in the list) or a dict
(with arbitrary keys that are stored)? I said "object" in the subject,
but I want to support Python primitive types, class instances, extension
module types (array, dictproxy, dbm, gdbm, etc.), and any future types.

I've thought about looking for keys(), looking for the special method names
that allow you to override indexing behavior, and looking at the class or
type of the object. I could be wrong, but I don't think any of those
strategies will work with all arguments.

Thanks,

-- Derek
Aug 23 '06 #1
6 1680
Derek Peschel wrote:
I've thought about looking for keys(), looking for the special method names
that allow you to override indexing behavior, and looking at the class or
type of the object. I could be wrong, but I don't think any of those
strategies will work with all arguments.
the behaviour of obj[arg] is determined by the __getitem__ method, and
that method can do whatever it wants.

</F>

Aug 23 '06 #2
Derek Peschel wrote:
Here are two functions.

def invert_dict_to_lists(dict):
lists = {}
for key in dict:
value = dict[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

def invert_list_to_lists(list):
lists = {}
for key in range(len(list)):
value = list[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

They are the same except for the expression in "for key in ...". Can they
be combined into one function? How can I determine if the argument is
like a list (with numeric indices that are not stored in the list) or a
dict
(with arbitrary keys that are stored)? I said "object" in the subject,
but I want to support Python primitive types, class instances, extension
module types (array, dictproxy, dbm, gdbm, etc.), and any future types.

I've thought about looking for keys(), looking for the special method
names that allow you to override indexing behavior, and looking at the
class or
type of the object. I could be wrong, but I don't think any of those
strategies will work with all arguments.
Instead of the (unreliable) introspection approach you could let the client
code decide:
>>def invert(pairs):
.... result = {}
.... for k, v in pairs:
.... if v in result:
.... result[v].append(k)
.... else:
.... result[v] = [k]
.... return result
....
>>invert(dict(a=1, b=2, c=1).iteritems())
{1: ['a', 'c'], 2: ['b']}
>>invert(enumerate([1,1,2,3]))
{1: [0, 1], 2: [2], 3: [3]}

Peter
Aug 23 '06 #3
Derek Peschel <dp******@eskimo.comwrote:
Here are two functions.

def invert_dict_to_lists(dict):
lists = {}
for key in dict:
value = dict[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

def invert_list_to_lists(list):
lists = {}
for key in range(len(list)):
value = list[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

They are the same except for the expression in "for key in ...". Can they
be combined into one function? How can I determine if the argument is
They can easily be refactored, if that's what you mean:

def _invert_internal(container, keys):
lists = {}
for key in keys:
value = container[key]
if not value in lists:
lists[value] = [key]
else:
lists[value].append(key)
return lists

def invert_dict_to_lists(adict):
return _invert_internals(adict, adict)

def invert_list_to_lists(alist):
return _invert_internals(alist, xrange(len(alist)))

I've also performed a few other minor enhancements (never name things
dict or list because that hides the builtin types, use xrange vs range).
I have not changed the 4 lines in the if/else though I don't like them
(if not.../else is a very confusing construct -- at a minimum I'd
rephrase it as if/else swapping the bodies of the two clauses).

If you want to add a generic form accepting either lists or dicts you
need a try/except statement inside it, e.g.:

def invert_generic(container):
try:
container['zap']
except TypeError:
keys = xrange(len(container))
except KeyError:
keys = container
else:
keys = container
return _invert_internal(container, keys)

Of course there are all sort of fragilities here -- e.g., something like
invert_dict_to_lists({23:[45]}) will crash and burn. But that's quite
separate from the issue of distinguishing a dict from a list, which is
what the generic function is doing, showing how to handle exceptions for
the purpose. Of course, there's no way to use a "totally" generic
container, because there are no real limits to the keys it may accept
(including infinite sets thereof, computing values in __getitem__).
Alex
Aug 23 '06 #4
In article <1h**************************@mac.com>, Alex Martelli wrote:
>Derek Peschel <dp******@eskimo.comwrote:
>They are the same except for the expression in "for key in ...". Can they
be combined into one function? How can I determine if the argument is

They can easily be refactored, if that's what you mean:
No, that isn't what I mean. I wanted _one_ function that works with a wide
variety of objects -- anything that has a finite number of keys you can
iterate over, with each key mapping to a finite number of values, and the
key iteration and value lookup referentially transparent. This hypothetical
function would have to do some checking of the argument type, but hopefully
as little as possible. It should work with object types invented after it
was written.

Reading everyone's replies, especially yours and Fredrik Lundh's, I realized
I've been thinking of the whole problem in Smalltalk (or possibly Ruby)
terms. Smalltalk and Ruby use inheritance to describe some properties of
objects. Python has many primitive types that aren't related to eaach other.
I thought that testing for methods might get the properties I wanted, but
you two pointed out that the method writer has too much latitude. Do you
think the generic-function idea is still useful?

At the moment I only need to invert dicts and lists. Is subclassing dict
and list considred good style? (I see I can't add methods to dict and list
directly.)
>I've also performed a few other minor enhancements (never name things
dict or list because that hides the builtin types, use xrange vs range).
OK, I'll remember those points. The argument names are a style I got
from my Ruby code, and possibly not a good idea there either.
>I have not changed the 4 lines in the if/else though I don't like them
(if not.../else is a very confusing construct -- at a minimum I'd
rephrase it as if/else swapping the bodies of the two clauses).
It used if/else originally. Then I swapped the parts of the conditional
to make the inversion function match another function (that takes a key,
old value, and new value, and makes the change in a sequence and in its
inverted form). To me the swapped version made some sense in the second
function, because of the layout of the function as a whole, but you have
a point that if not/else is rarely (never?) clear.
>If you want to add a generic form accepting either lists or dicts you
need a try/except statement inside it, e.g.:
Is that a reliable way to get the properties I wanted?

RADLogic Pty. Ltd. added a two-way dict package to the Cheese Shop. It
requires that the mapping be one-to-one, which won't work for me. It sub-
classes dict, and requires that keys and values be hashable.

-- Derek
Aug 26 '06 #5
In article <ec************@news.t-online.com>, Peter Otten wrote:
>Instead of the (unreliable) introspection approach you could let the client
code decide:
See my reply to Alex Martelli's post, where I explain my original desire
for one function that works with a wide variety of present and future
object types. Your solution accomplishes that, but only by forcing the
caller to convert the argument to a list of pairs. If the caller knows the
type it's going to pass down, that's easy. If the caller doesn't know,
your approach doesn't seem any easier than mine.

In practice, with my needs of inverting dicts and lists, your solution might
not be a bad one.

-- Derek
Aug 26 '06 #6
Derek Peschel wrote:
At the moment I only need to invert dicts and lists. Is subclassing dict
and list considred good style?
if it makes sense for your application, sure.

however, it might be more convenient to just use a simple type check
(e.g. looking for items) to distinguish between "normal mappings" and
"normal sequences".

try:
items = obj.items()
except AttributeError:
items = enumerate(obj) # assume it's a sequence

</F>

Aug 26 '06 #7

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

Similar topics

13
by: ajikoe | last post by:
Hi, How do I know type of simple object is tuple or list or integer, for example my function should understand what is the object type passed in its argument Pujo
2
by: John Spiegel | last post by:
Hi all, I'm trying to create a subclass of an ArrayList that is intended specifically for holding FileInfo objects. My idea to restrict this is to override the Add and AddRange methods to allow...
7
by: Bennett Haselton | last post by:
Is there any way to find a string representing an object's class, which will work in Internet Explorer 6? "typeof" doesn't work -- it returns "object" for all objects: x =...
5
by: verec | last post by:
I just do not understand this error. Am I misusing dynamic_cast ? What I want to do is to have a single template construct (with no optional argument) so that it works for whatever T I want to...
4
by: Tamir Khason | last post by:
How can I set the type of the object added to ArrayList (type of Array List Members) Here is the code: protected ArrayList tabs = new ArrayList(); public ArrayList Tabs {
14
by: Matt | last post by:
I want to know if "int" is a primitive type, or an object? For example, the following two approaches yield the same result. > int t1 = int.Parse(TextBox2.Text); //method 1 > int t2 =...
6
by: Darryn Ross | last post by:
Hi... I am not sure how to test the type of an object that i define object a = "test" ; object b = 1 ; object c = true ; how do i test each of the three objects to find out what types they...
5
by: Random | last post by:
How can I use reflection (or some other method) to find the type of an object that has been passed in to my method under an interface definition? I try to use GetType, but that won't work.
0
by: Matt Nunnally | last post by:
I have a .NET dll that I'm using in Vb6. After registering with regasm and referencing the tlb, I am unable to compile when I call properties declared as LONG in my VB.NET dll. I get an error...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.