473,805 Members | 2,154 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
On Jun 23, 11:45 am, walterbyrd <walterb...@ina me.comwrote:
On Jun 22, 11:43 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
Can you help us understand, by showing a use case that would in your
estimation be improved by the feature you're describing?

Suppose you are sequentially processing a list with a routine that
expects every item to be of a certain type. Something in the list that
doesn't conform to the type could give you unexpected results, maybe
crash your application.
if hasattr(elmt, some_func):
elmt.some_func( )

Jun 23 '07 #11
In <11************ **********@e16g 2000pri.googleg roups.com>, walterbyrd
wrote:
On Jun 22, 11:43 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
>Can you help us understand, by showing a use case that would in your
estimation be improved by the feature you're describing?

Suppose you are sequentially processing a list with a routine that
expects every item to be of a certain type. Something in the list that
doesn't conform to the type could give you unexpected results, maybe
crash your application.
It raises an exception. What want you an "typed list" to do when a wrong
object is put into it? Raising an exception? So all you change is the
point in time when the exception is raised.
In python, as far as I know, there is nothing built into the language
to keep any type of item from being included in a list - or any such
structure. To me, that seems like a potentially vulnerability.
Especially since variables in python do not have to be explicitly
assigned - another variable that points to the same thing, could
change the data that a variable points to.
But this doesn't really change with a "typed list". It's easy to take
an object and completely replace all its attributes so it behaves very
different.

Ciao,
Marc 'BlackJack' Rintsch
Jun 23 '07 #12
On Jun 23, 6:45 pm, walterbyrd <walterb...@ina me.comwrote:
On Jun 22, 11:43 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
Can you help us understand, by showing a use case that would in your
estimation be improved by the feature you're describing?

Suppose you are sequentially processing a list with a routine that
expects every item to be of a certain type. Something in the list that
doesn't conform to the type could give you unexpected results, maybe
crash your application.

In python, as far as I know, there is nothing built into the language
to keep any type of item from being included in a list - or any such
structure. To me, that seems like a potentially vulnerability.
Especially since variables in python do not have to be explicitly
assigned - another variable that points to the same thing, could
change the data that a variable points to.
Reminds me a bit of that (awful) sketch:
Patient: Doctor doctor it hurts if I do that.
Doctor: Well don't do that then.

The data for the list should have been checked when it entered
your program. It is up to you to then only stuff the list with
data expected by the routine. If you don't then Python will most
likely throw a runtime exception, but it is up to you to trust
your co-workers on the project.

- Paddy

Jun 23 '07 #13
7stud wrote:
On Jun 23, 11:45 am, walterbyrd <walterb...@ina me.comwrote:
>Suppose you are sequentially processing a list with a routine
that expects every item to be of a certain type. Something in the
list that doesn't conform to the type could give you unexpected
results, maybe crash your application.

if hasattr(elmt, some_func):
elmt.some_func( )
Personally, I prefer

try:
elmt.some_func( )
except AttributeError:
# do stuff

Regards,
Björn

--
BOFH excuse #130:

new management

Jun 24 '07 #14
walterbyrd <wa********@ina me.comwrites:
Suppose you are sequentially processing a list with a routine that
expects every item to be of a certain type. Something in the list
that doesn't conform to the type could give you unexpected results,
maybe crash your application.
A routine that demands its inputs to be of a certain *type*, rather
than requiring that the implement the required *behaviour*, breaks
polymorphism.

Polymorphism is considered valuable in Python; search for any of
"polymorphi sm", "duck typing" and "easier to ask forgiveness than
permission".

--
\ "Intellectu al property is to the 21st century what the slave |
`\ trade was to the 16th." -- David Mertz |
_o__) |
Ben Finney
Jun 24 '07 #15
walterbyrd a écrit :
On Jun 22, 11:43 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:

>>Can you help us understand, by showing a use case that would in your
estimation be improved by the feature you're describing?


Suppose you are sequentially processing a list with a routine that
expects every item to be of a certain type.
it should expects every item to support a given protocol (expose a given
interface, have a given set of attributes, whatever...).

OOP is not about "types" or "classes", it's about objects. And in a
dynamic language like Python, where you can add/remove/replace almost
each attribute (including methods and even it's class...) of an object
at runtime, override the way the attribute look-up is done, etc, this is
specially true.

The fact that an object is an instance of a given class doesn't
necessarily imply that it supports the same protocol. And the fact that
an object is an instance of a given class is only true at a given
time... So testing on type to allow inclusion of an object in a list for
"type safety" reasons is mostly a waste of time. It's also
counter-productive since it would reject objects that actually supports
the right protocol but are not of the "correct type".
Something in the list that
doesn't conform to the type
s/conform to the type/support the protocol/
could give you unexpected results, maybe
crash your application.
Yes. But... you do test your application, don't you ?-)
In python, as far as I know, there is nothing built into the language
to keep any type of item from being included in a list
No. cf above.
- or any such
structure. To me, that seems like a potentially vulnerability.
Did you actually had some effective problem with this ?
Especially since variables in python do not have to be explicitly
assigned
???

I suppose you meant something else here, probably about declarative typing ?
- another variable that points to the same thing, could
change the data that a variable points to.
Give me a reference to an object in a list, and I can change almost any
attribute of the object - even it's class.

FWIW, a similar - but usually much much worse wrt/ possible results -
problem exists in C with pointers and memory.

I came to Python from statically typed languages, and first had a
similar reaction. It took me some time to believe it, but type errors
are quite less frequent that you would imagine, and most of the time
quite trivial to spot and fix. I've had bigger problems with memory
handling and dangling pointers in C, Pascal or C++.
Jun 24 '07 #16
On Jun 24, 10:31 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
Especially since variables in python do not have to be explicitly
assigned

???
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.

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}.

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.

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.

But, I think sometimes it's helpful to use a structure that is little
more restrictive, to sort of enforce a degree of integrity. An example
I have already given: why use tuples instead of a list? Tuples are
actually a bit more restrictive.

I don't think there is anything wrong with the data structures that
exist in python. I was just wondering if there was a structure that
would restrict a collection to only allow certain types. The
"restrictedlist " class discussed in another thread may be the sort of
thing I was looking for.

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.

Jun 25 '07 #17
I don't think there is anything wrong with the data structures that
exist in python. I was just wondering if there was a structure that
would restrict a collection to only allow certain types. The
"restrictedlist " class discussed in another thread may be the sort of
thing I was looking for.

Just remenber that if you write a library using such a thing, your
(consenting adults) users will not be able to store objects in your
list that implement (part of) the interface of the type that you
restricted.
--
EduardoOPadoan (eopadoan->altavix::com )
Bookmarks: http://del.icio.us/edcrypt
Jun 25 '07 #18
On 2007-06-25, walterbyrd <wa********@ina me.comwrote:
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.
It might be a pointless new spelling for the .split method.

x = 'Smith, Ted, 15 Smedly Rd."
last, first, street = x / ', '

Tongue-in-cheekily-yours,

--
Neil Cerutti
Strangely, in slow motion replay, the ball seemed to hang in the air for even
longer. --David Acfield
Jun 25 '07 #19
walterbyrd a écrit :
On Jun 24, 10:31 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :

>>>Especially since variables in python do not have to be explicitly
assigned

???


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.
You haven't changed b, you have changed the object bound to name 'b'.
Which happens to be also bound to name 'a'.
After I
assigned a to b,
Well, I guess the term "assignment " is misleading you then. "binding"
would be more accurate - you bound names 'a' and 'b' to the same object.
Then, whether you access this object via name 'a' or name 'b', you're
still accessing the same object.
I never did another "b =" yet b changed anyway
Doing 'b = some_other_obje ct' would still not 'change b' - you don't
change a name - but rebind name 'b' to another object.

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.
because I changed a. I am not saying there is anything wrong with
this, I'm just explaining what I meant.

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}.

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.
Yes - assuming names L, X, Y and Z are bound to the same list.

And it would also crash if one the dicts was modified between the moment
it is added to the list and the moment you pass the list to your
function. Which makes "typed" lists totally useless anyway. And even if
you use a smarter 'correctness' test (like a callback function checking
that every item added or inserted supports keying and has the correct
keys), it would still be useless since you could still manage to modify
one of the items of the list *after* it has been added to it.
Of course, you can always work around this by just programming very
carefully,
You do program carefully, don't you ?-)
and doing a lot of error checking.
That's usually not even necessary - most of the time (ie: almost
always), you'll have a nice traceback in the minutes following the
moment you introduced the error.
That is always true in
any language.
Nope. In Python, you seldom have to do error *checking* - the language
do it for you (that's what exceptions are for). What you have to do is
1/ testing, and 2/ error *handling*.

Now did you actually had any effective problem with Python's dynamism ?
Or are you 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.
But, I think sometimes it's helpful to use a structure that is little
more restrictive, to sort of enforce a degree of integrity.
Sometimes you do have to check the validity of the data you are supposed
to work on, true - mostly when it comes to program inputs (be it wia
files, sockets, forms, environment, whatever). Once this is done, you
shouldn't have to worry too much - just let Python crash when there's
something wrong, carefully read the traceback, and correct the offending
code (which is very likely in the last modifications you made).
An example
I have already given: why use tuples instead of a list? Tuples are
actually a bit more restrictive.
You don't use tuples "instead of" lists. Lists are collections, tuples
are structured data.
I don't think there is anything wrong with the data structures that
exist in python. I was just wondering if there was a structure that
would restrict a collection to only allow certain types.
Not builtin. You can roll your own if it makes you happy, but that would
be a waste of time - been here, done that, you see...
The
"restrictedlist " class discussed in another thread may be the sort of
thing I was looking for.
So please take time to read the whole thread.
BTW: I think polymorphism is great and all. But it does have (and IMO
should have) it's limitations.
Yes, indeed - if an object doesn't understand a message, then you have
an exception. But since the only way to know if an object can handle a
message is to send the message (please refer to my previous post),
enforcing 'type'-based (with 'type'=='class' ) restriction in Python is
not only useless, it's also harmful. IOW, stop fighting against the
language - just use it.
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).
Jun 25 '07 #20

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
9186
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...
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
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
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.