473,805 Members | 2,119 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Collections of non-arbitrary objects ?

Python seems to have a log of ways to do collections of arbitrary
objects: lists, tuples, dictionaries. But what if I want a collection
of non-arbitrary objects? A list of records, or something like that?

Jun 21 '07
28 1615
In <46************ ***********@new s.free.fr>, Bruno Desthuilliers wrote:
walterbyrd a écrit :
>For example, I don't think you can divide a string by another string.

No, because this operation is not implemented for strings - IOW, strings
doesn't understand this message. What would be the meaning of dividing
strings anyway ? (while concatening string is a well-known operation).
As someone else already mentioned dividing strings is splitting. The Pike
language does this:

http://pike.ida.liu.se/generated/man...chapter_4.html

Scroll down to ``string / string``. The definition of ``string / float``
is neat too. Something I really miss in everyday programming in Python,
not. ;-)

Ciao,
Marc 'BlackJack' Rintsch
Jun 25 '07 #21
walterbyrd <wa********@ina me.comwrites:
>a = [1,2,3]
b = a
a[1] = 'spam'

Here, I have changed b, without an explicit assignment.
No. Both 'a' and 'b' are names bound to a single object; you're
changing that object. This is a subtle difference, but it's one that
is confusing you in this instance.
So let's say I have list L, and I have a routine that expects every
item in L to be a dictionary like: {'name':'joe', 'job':'dev',
'pay': min_wage}.
If that routine expects objects of a particular *type*, instead of
objects that exhibit expected *behaviour*, the routine is poorly
designed.
Not only could the app crash if an incorrect item where inserted
into L. But the app could crash if an incorrect item were inserted
in lists X,Y, or Z.
When the routine tries to deal with an object that doesn't behave as
expected, an exception will be raised. If the exception goes uncaught,
then Python will exit and throw the exception to the user; I suppose
you could call this a "crash".
Of course, you can always work around this by just programming very
carefully, and doing a lot of error checking. That is always true in
any language.
Better is to catch the exception at a level where it can be dealt
with; this is usually the same level where those non-conforming
objects were placed in the list to begin with.
BTW: I think polymorphism is great and all. But it does have (and
IMO should have) it's limitations. For example, I don't think you
can divide a string by another string.
Indeed, and you'll get an exception raised if you try. Catch that
exception at a level where there's enough context to make sense of it,
and deal with it in whatever way you see fit.

--
\ "Imagine a world without hypothetical situations." -- Anonymous |
`\ |
_o__) |
Ben Finney
Jun 25 '07 #22
Bruno Desthuilliers <bd************ *****@free.quel quepart.frwrite s:
You know, Python is now something like 17 years old, and is used by a
*lot* of peoples for a *lot* of programs - some of them far from
trivial. I think you can be confident in this experience. IOW, just
write your code, and you'll find out that the kind of problems you
seem to fear so much will not happens that often.
Assembler and Cobol have been around even longer...
Jun 26 '07 #23
En Mon, 25 Jun 2007 11:14:23 -0300, walterbyrd <wa********@ina me.com>
escribió:
I have probably expressed this incorrectly. What I meant was:
>>>a = [1,2,3]
b = a
a[1] = 'spam'

Here, I have changed b, without an explicit assignment. After I
assigned a to b, I never did another "b =" yet b changed anyway
because I changed a. I am not saying there is anything wrong with
this, I'm just explaining what I meant.
I think you should benefit reading this short article:
http://effbot.org/zone/python-objects.htm

--
Gabriel Genellina

Jun 26 '07 #24
On Jun 25, 8:21 pm, Marius Gedminas <mged...@gmail. comwrote:
On Jun 24, 2:12 pm, Bjoern Schliessmann <usenet-

mail-0306.20.chr0n.. .@spamgourmet.c omwrote:
7stud wrote:
if hasattr(elmt, some_func):
elmt.some_func( )
Personally, I prefer
try:
elmt.some_func( )
except AttributeError:
# do stuff

That also hides attribute errors that occur within some_func. I think
I'd rather know when elmt has an implementation of some_func that is
buggy. Thus I prefer the hasattr version.
Or possibly

try:
do_func = elmt.some_func
except AttributeError:
do_stuff()
else:
do_func()

(internally hasattr is doing that anyway).

Michele Simionato

Jun 26 '07 #25
On Jun 24, 10:31 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :

You perhaps don't know this, but most statically typed languages have
the notion of either pointers or references, that can cause similar -
and usually worse - problems.
Yes, but those languages also have the notion of structures that do
not allow arbitrary collections. That is what I was wondering about
when I started the thread. It's fine that python has four different
ways of creating collections of arbitrary data types, but I thought it
might be helpful if python had, at least, one way of a creating a
collection of non-arbitrary data.
>
You do program carefully, don't you ?-)
I try. But things like typos are a normal part a life.
>
Now did you actually had any effective problem with Python's dynamism ?
Or are you just scared ?
Just scared.
You know, Python is now something like 17 years old, and is used by
a
*lot* of peoples for a *lot* of programs - some of them far from
trivial. I think you can be confident in this experience. IOW, just
write your code, and you'll find out that the kind of problems you seem
to fear so much will not happens that often.
Of course, BASIC is over 40 years old, also used by a *lot* of people.
A lot of non-trivial apps have been written in BASIC. But, BASIC is
often criticized for it's lack of structure. A language's longevity,
and/or popularity, don't mean there isn't room for improvement. Guido
must think python has a lot of room for improvement since he's
completely throwing out backward compatibility with python 3000.
>
You don't use tuples "instead of" lists. Lists are collections, tuples
are structured data.
It seems to me that tuple are essentially immutable lists. So why
impose that immutability restriction on a data collection? Why not
just have lists and not tuples? What can a tuple do that a list can
not do? Why was python designed so that tuples could be used for
dictionary indexes, but not lists? Could it be because imposing that
restriction on a data collection insures a certain degree of
integrity? My point is: sometimes imposing some restrictions can give
a degree in built-in integrity. Maybe you don't need that integrity
insurance, if you code carefully enough, but can you always count on
that?

BTW: I'm not assuming that it will always be me running my own app.
Sure, if an exception occureed while I was running my own app, I'd
probably know what to do. But if somebody else (who - god forbid -
didn't know python was running the app, things might be more difficult.

Jun 26 '07 #26
walterbyrd a écrit :
>>On Jun 24, 10:31 pm, Bruno Desthuilliers
<bdesth.quelq uech...@free.qu elquepart.frwro te:
You perhaps don't know this, but most statically typed languages have
the notion of either pointers or references, that can cause similar -
and usually worse - problems.

Yes, but those languages also have the notion of structures that do
not allow arbitrary collections.
Ever played with casting in C ?
That is what I was wondering about
when I started the thread. It's fine that python has four different
ways of creating collections of arbitrary data types, but I thought it
might be helpful if python had, at least, one way of a creating a
collection of non-arbitrary data.
As I explained, while technically possible (and not specially
difficult), this is a waste of time given Python's dynamism.
>You do program carefully, don't you ?-)

I try. But things like typos are a normal part a life.
So are they in any language. I fail to see much difference here.
>Now did you actually had any effective problem with Python's dynamism ?
Or are you just scared ?
Just scared.
So take a deep breath and try to just do the simplest thing (in this
case: using builtin collection types). Usually, it JustWorks(tm).
You know, Python is now something like 17 years old, and is used by
a
>*lot* of peoples for a *lot* of programs - some of them far from
trivial. I think you can be confident in this experience. IOW, just
write your code, and you'll find out that the kind of problems you seem
to fear so much will not happens that often.

Of course, BASIC is over 40 years old, also used by a *lot* of people.
Not the same kind of people I'd say !-)
A lot of non-trivial apps have been written in BASIC. But, BASIC is
often criticized for it's lack of structure.
Old time basic effectively lacks of "structure" , since it uses goto's
instead of functions, loops and conditionals (google for "structured
programming").

What I meant here is that one of the lessons of this collective
experience is that 'typed' containers are more often harmful than useful.
A language's longevity,
and/or popularity, don't mean there isn't room for improvement.
Indeed. But declarative static typechecking wouldn't be an improvement.
Guido
must think python has a lot of room for improvement since he's
completely throwing out backward compatibility with python 3000.
Not "completely throwing out". Just allowing *some* major breakages -
the kind you usually get with each major release of other languages, but
that Python managed to avoid as much as possible so far.
>You don't use tuples "instead of" lists. Lists are collections, tuples
are structured data.

It seems to me that tuple are essentially immutable lists.
They are not (even if you can use them that way too). FWIW and IIRC,
this is a FAQ.
So why
impose that immutability restriction on a data collection?
Because tuples are *not* collections. They are *structured data*. The
canonical tuple is a SQL database row.
Why not
just have lists and not tuples?
because tuples are not lists.
What can a tuple do that a list can
not do?
Be immutable.
Why was python designed so that tuples could be used for
dictionary indexes, but not lists?
How would you compute a hash from a generic mutable collection ?
Could it be because imposing that
restriction on a data collection insures a certain degree of
integrity?
Once again: tuples are *not* collections. Would you define a string as a
collection ?
My point is: sometimes imposing some restrictions can give
a degree in built-in integrity.
Yes. But the kind of restriction you're talking about won't buy you
much, as I already explained, and, in practice, happens to be mostly
useless.
Maybe you don't need that integrity
insurance, if you code carefully enough,
Maybe you don't need that "integrity insurance", period ?-)
but can you always count on
that?
It seems that tens of thousands of Python users are doing fine without this.
BTW: I'm not assuming that it will always be me running my own app.
Sure, if an exception occureed while I was running my own app, I'd
probably know what to do. But if somebody else (who - god forbid -
didn't know python was running the app, things might be more difficult.
The canonical solution is to have an application-level error handler
that logs uncaught exceptions (so the developper can get at them),
display a user-friendly error message (eventually giving the user a way
to submit a bug report to the developper), and try to crash as cleanly
as possible.

However careful and serious you are wrt/ programming and testing, your
program *will* have bugs (unless it's some kind of hello world). Better
learn to live with it.

Let's suppose you implement a restrictedList. It of course raises an
exception when trying to add a 'non-compliant' item. All this happening
at runtime, of course. Now let's suppose there's one such error in your
code that managed to pass thru tests. What's going to happen ? Yes,
exactly the same thing as if you used a plain list - just somewhere else
in the code. For the final user, the result will be *exactly* the same :
a crash.
Jun 26 '07 #27
>
Did you try to sort a tuple ?
>>(1, "aaa").sort ()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'sort'
I can do this:
>>x = (3,2,1)
x = tuple(sorted(li st(x)))
Which, although senseless, effectively sorts the x tuple. But, you are
right, I am not really sorting the tuple, I'm sorting a list, which
has been made from the tuple, then changing it back to a tuple.

Actually, I can even do it in one line:

x = tuple(sorted(li st((3,2,1))))
Jun 28 '07 #28
walterbyrd wrote:
I can do this:
x = tuple(sorted(li st((3,2,1))))
The list() conversion is superfluous:
>>tuple(sorted( (3,2,1)))
(1, 2, 3)

Peter

Jun 28 '07 #29

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

Similar topics

2
1436
by: Peter Dobcsanyi | last post by:
Dear All, I have just read PEP-320 and noticed the following comments regarding the "collections" package: ... - ? bag (only if use cases established) ... I would like to argue for such a use case. We at designtheory.org are
8
1812
by: Arnaud Debaene | last post by:
Hello all, One area where the .Net framework 1.1 is really poor is Collections : We've got very few choice concerning the containers and their characteristics (for example, ArrayList, Queue and Stack are the only "non-dictionary" avalaible containers, and only Stack has some complexity specifications). The worst thing however is the IEnumerator interface, which doesn't allow for insertion, deletion or even *modification* of an item...
24
1713
by: Gary van der Merwe | last post by:
Hi When C# 2.0 arrives System.Collections.Specialized.StringCollection will become "obsolete". Will the framework still contain this class, or will there be a C# 1.X to 2.0 conversion utility that will change System.Collections.Specialized.StringCollection to System.Collections.ArrayList <string> and ArrayList to ArrayList<object> ?? Gary
1
2594
by: Tim T. | last post by:
I'm currently working on a report to forecast production for finished goods. The user can select one or more items to forecast. In addition, they may select one or more warehouses to view breakdowns for as well as one or more customers. Now, the report iterates through the selected items in the finished good listbox. For each item that it comes across, it calls 4 routines to gather various totals. Each routine will gather a total for...
4
2158
by: John Dalberg | last post by:
I noticed the starterkits timetracker & issue tracker load data from a database into custom collections (arraylists) which bind to a datagrid. What are the advantages of using custom collections over simpler objects like datareaders or datatables? John Dalberg
4
8194
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from System.Collections.Generic.Queue? Putting it another way can I safely replace a System.Collections.Queue.Synchronized(myUnSynchronizedQueue) with a System.Collections.Generic.Queue while porting a working 2003 project? Thanks,
11
1676
by: CMM | last post by:
First let me say that maybe I'm having a "duh" moment and perhaps I'm missing something... but it seems to me that no one thing in the System.Collections namespace (even in .NET 2.0) even comes close to the still-useful-today VB intrinsic Collection. Here's the challenge (I know I'm totally missing something here).... Implement a full featured MRU (Most Recently Used) list using System.Collections. Use Case:
25
3042
by: Lars | last post by:
Hi, I have a base class holding a generic list that needs to be accessed by both the base class and its subclasses. What is the best solution to this? I am fairly new to generics, but I am aware of that fact that if you have a class B, that inherits from A, then List<Bdoes NOT inherit from List<A>. So I understand why the example below does not compile, but I fail to
2
7365
by: Fred Heida | last post by:
Hi, i'm trying to (using managed C++) implment the IEnumerable<Tinterface on my class.. but have a problem with the 2 GetEnumerator method required.... what i have done is... generic<typename T> public ref class SetOfProxy : public System::Collections::Generic::IEnumerable<T>
4
1764
by: Giorgio Parmeggiani | last post by:
Hi I am using the svcutil parameter: /ct to obtain IBindingList from WCF Service. I can exclude some collection or some WCF service methods from this conversion? I have some strongly typed custom collections, which are serializable, and I want, sometime, to use my custom collection, not IBindingList. Thank in advance
0
9718
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
9596
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
10363
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
10368
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
10107
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
7649
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
5544
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
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

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.