473,403 Members | 2,222 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,403 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 1688
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.