473,797 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1701
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(enumer ate([1,1,2,3]))
{1: [0, 1], 2: [2], 3: [3]}

Peter
Aug 23 '06 #3
Derek Peschel <dp******@eskim o.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_interna l(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_interna ls(adict, adict)

def invert_list_to_ lists(alist):
return _invert_interna ls(alist, xrange(len(alis t)))

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(cont ainer))
except KeyError:
keys = container
else:
keys = container
return _invert_interna l(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******@eskim o.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
1686
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
340
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 only FileInfo objects. In AddRange, how can I verify that the collection passed is a collection of FileInfo objects? TIA,
7
42576
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 = window.open('http://www.yahoo.com/'); alert(typeof x); And I found this page: http://www.mozilla.org/js/language/js20-2002-04/core/expressions.html
5
8731
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 use it with. Now, if that T happens to be some subclass of a known base class (object, in this case), I want to perform some extra stuff ... I've read Faq#35, and the most natural solution would have
4
7089
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
7449
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 = System.Int32.Parse(TextBox2.Text); //method 2 And people said "int" is a C# alias for "System.Int32". If this is the case, can we say "int" is an object??
6
1743
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 are.. e.g string, int, bool???
5
1589
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
937
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 something to the effect of Function or Interface restricted, Automation type not supported. Any ideas?
0
9685
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
9536
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
10245
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
10205
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
9063
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6802
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4131
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.