py3k: converting int to bytes
Is there a better way to convert int to bytes then going through strings: x=5 str(x).encode() Thanks. -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
py3k: datetime resolution / isoformat
When I do:
datetime.datetime.now().isoformat(' ')
I get the time with the microseconds. The docs says:
"if microsecond is 0 -MM-DDTHH:MM:SS+HH:MM".
How do I set microsecond to 0?
>>> datetime.datetime.microsecond = 0
Traceback (most recent call last):
File "", line 1, in
TypeError: can't set attributes of built-in/extension type
'datetime.datetime'
>>> datetime.datetime.resolution = (0, 0, 0)
Traceback (most recent call last):
File "", line 1, in
TypeError: can't set attributes of built-in/extension type
'datetime.datetime'
Do I need to create my own class to extend datetime.datetime?
--
Yves. http://www.SollerS.ca/
http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list
Re: Memory deallocation
Steven D'Aprano wrote: On Mon, 19 Oct 2009 00:30:30 -0700, dheeraj wrote: Hi, a program of mine is being terminated by the OS as it uses too much memory. I guess this is due to static memory allocation I've also tried to use "del" but in vain. Is there any other function that performs the above operation and frees the allocated memory?? del is what you should use. You won't see memory reduction for that process, but the memory will be available for other other objects and prevent a growth of the memory footprint for that process. I would expect in general that Python will fail with a MemoryError exception before the operating system terminates the process for using too much memory. What are you doing in your program? What version of Python are you using and what OS? You need to give more information for us to be more helpful. I have seen cases with large dictionaries of large-ish objects where the machine ends up trashing. -- Yves. http://www.sollers.ca/ -- http://mail.python.org/mailman/listinfo/python-list
email.encoders.encode_base64 creates one line only
This is with python 3.1.2 (r312:79147). I have not tried with 2.7. When I create an attachment with email.mime.image.MIMEImage, by default it uses email.encoders.encode_base64 for the encoder, but that results in a single line base64 string, instead of the recommended multiple 76-chars lines. This works with most MTA and MUA, but some of them choke on it. Is this a bug, or do I need to write my own _encoder? -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: email.encoders.encode_base64 creates one line only
This is with python 3.1.2 (r312:79147). I have not tried with 2.7. When I create an attachment with email.mime.image.MIMEImage, by default it uses email.encoders.encode_base64 for the encoder, but that results in a single line base64 string, instead of the recommended multiple 76-chars lines. This works with most MTA and MUA, but some of them choke on it. In case somebody runs into the same issue: http://bugs.python.org/issue9298 And I added a work around if you need a solution before this bug is fixed at: http://bugs.python.org/issue11156#msg128213 -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
return an object of a different class
How can I do something like this in python: #!/usr/bin/python3.1 class MyNumbers: def __init__(self, n): self.original_value = n if n <= 100: self = SmallNumers(self) else: self = BigNumbers(self) class SmallNumbers: def __init__(self, n): self.size = 'small' class BigNumbers: def __init__(self, n): self.size = 'big' t = MyNumbers(200) When I do type(t) it says MyNumbers, while I'd want it to be BigNumbers, because BigNumbers and SmallNumbers will have different methods etc... Do I need to use metaclasses? Thanks. -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: return an object of a different class
On 11-02-15 07:45 PM, alex23 wrote: Firstly, does MyNumbers _have_ to be a class? Or would a function acting as a class factory be sufficient? Yes it does. I didn't explain my problem, chose a terrible example. This is more what I'm trying to do: class thingy: def __init__(self, athingy): self.basic_extract() if self.sortof = def basic_extract(self): do a bunch of things self.sortof = .. def general_method(self) class ThingyTypeA: def __init__(self): further_extract() class ThingyTypeB: def __init__(self): further_extract() Otherwise, you can change the class of an object, even within its own methods: And then I just call __init__ method? class MyNumbers(object): def __init__(self, n = 0): self.original_value = n self.__class__ = BigNumbers if n> 100 else SmallThing self.__init__() class BigNumbers(MyNumbers): def __init__(self): size = 'big' self.newvalue = self.original_value * y class SmallNumbers(MyNumbers): def __init__(self): size = 'small' self.newvalue = self.original_value * x Hope this helps. Yes, thanks! -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: return an object of a different class
I didn't explain my problem, chose a terrible example. This is more what I'm trying to do: class thingy: def __init__(self, athingy): self.basic_extract() if self.typeof = A .../... def basic_extract(self): # complicated logic to extract data out of the thingy here # and set a bunch of values base on the data we extract self.size = xxx self.typeof = yyy self.weight = zzz def general_method(self) # Method that can be used on both types of thingy class ThingyTypeA: def __init__(self): # do some further extraction specific to type A further_extract() class ThingyTypeB: def __init__(self): # do some further extraction specific to type B further_extract() -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: return an object of a different class
I didn't explain my problem, chose a terrible example. This is more what I'm trying to do: Basically the subclass I want to use is based on some of the data I extract from a blob of data. If I use a function to extract the data before I create the objects, then I need to do a bunch of assignments afterwards. Unfortunately, it's still very contrived, and the names don't give any suggestion as to what you're trying to achieve. Can you improve on that? class ThingyTypeA: def __init__(self): # do some further extraction specific to type A further_extract() class ThingyTypeB: def __init__(self): # do some further extraction specific to type B further_extract() Perhaps you want those classes to inherit from your base class. Have you done the Python tutorial? It covers inheritance and how to use it. Yes, I have done subclasing before, and yes ThingyTypeA and B should be subclassing Thingy -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Convention for C functions success/failure
Hello, What is the convention for writing C functions which don't return a value, but can fail? If I understand correctly, 1. PyArg_ParseTuple returns 0 on failure and 1 on success. 2. PySet_Add returns -1 on failure and 0 on success. Am I correct? What should I do with new C functions that I write? Thanks, Noam -- http://mail.python.org/mailman/listinfo/python-list
Why keep identity-based equality comparison?
Hello,
Guido has decided, in python-dev, that in Py3K the id-based order
comparisons will be dropped. This means that, for example, "{} < []"
will raise a TypeError instead of the current behaviour, which is
returning a value which is, really, id({}) < id([]).
He also said that default equality comparison will continue to be
identity-based. This means that x == y will never raise an exception,
as is the situation is now. Here's his reason:
> Let me construct a hypothetical example: suppose we represent a car
> and its parts as objects. Let's say each wheel is an object. Each
> wheel is unique and we don't have equivalency classes for them.
> However, it would be useful to construct sets of wheels (e.g. the set
> of wheels currently on my car that have never had a flat tire). Python
> sets use hashing just like dicts. The original hash() and __eq__
> implementation would work exactly right for this purpose, and it seems
> silly to have to add it to every object type that could possibly be
> used as a set member (especially since this means that if a third
> party library creates objects for you that don't implement __hash__
> you'd have a hard time of adding it).
Now, I don't think it should be so. My reason is basically "explicit is
better than implicit" - I think that the == operator should be reserved
for value-based comparison, and raise an exception if the two objects
can't be meaningfully compared by value. If you want to check if two
objects are the same, you can always do "x is y". If you want to create
a set of objects based on their identity (that is, two different
objects with the same value are considered different elements), you
have two options:
1. Create another set type, which is identity-based - it doesn't care
about the hash value of objects, it just collects references to
objects. Instead of using set(), you would be able to use, say,
idset(), and everything would work as wanted.
2. Write a class like this:
class Ref(object):
def __init__(self, obj):
self._obj = obj
def __call__(self):
return self._obj
def __eq__(self, other):
return isinstance(other, Ref) and self._obj is other._obj
def __hash__(self):
return id(self._obj) ^ 0xBEEF
and use it like this:
st = set()
st.add(Ref(wheel1))
st.add(Ref(wheel2))
if Ref(wheel1) in st:
...
Those solutions allow the one who writes the class to define a
value-based comparison operator, and allow the user of the class to
explicitly state if he wants value-based behaviour or identity-based
behaviour.
A few more examples of why this explicit behaviour is good:
* Things like "Decimal(3.0) == 3.0" will make more sense (raise an
exception which explains that decimals should not be compared to
floats, instead of returning False).
* You won't be able to use objects as keys, expecting them to be
compared by value, and causing a bug when they don't. I recently wrote
a sort-of OCR program, which contains a mapping from a numarray array
of bits to a character (the array is the pixel-image of the char).
Everything seemed to work, but the program didn't recognize any
characters. I discovered that the reason was that arrays are hashed
according to their identity, which is a thing I had to guess. If
default == operator were not defined, I would simply get a TypeError
immediately.
* It is more forward compatible - when it is discovered that two types
can sensibly be compared, the comparison can be defined, without
changing an existing behaviour which doesn't raise an exception.
My question is, what reasons are left for leaving the current default
equality operator for Py3K, not counting backwards-compatibility?
(assume that you have idset and iddict, so explicitness' cost is only
two characters, in Guido's example)
Thanks,
Noam
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why keep identity-based equality comparison?
> Can you provide a case where having a test for equality throw an > exception
> is actually useful? Yes. It will be useful because: 1. The bug of not
> finding a key in a dict because it was implicitly hashed by identity and not
> by value, would not have happened. 2. You wouldn't get the weird 3.0 !=
> Decimal("3.0") - you'll get an exception which explains that these types
> aren't comparable. 3. If, in some time, you will decide that float and
> Decimal could be compared, you will be able to implement that without being
> concerned about backwards compatibility issues. But there are certainly
> circumstances that I would prefer 1 == (1,2) to throw an exception
> instead of simply turning up False. >>> So what are they? > > Again - give
> us real use cases. You may catch bugs earlier - say you have a
> multidimensional array, and you forgot one index. Having comparison raise an
> exception because type comparison is meaningless, instead of returning False
> silently, will help y!
ou catch your problem earlier. Noam
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why keep identity-based equality comparison?
It seems to me that both Mike's and Fuzzyman's objections were that sometimes you want the current behaviour, of saying that two objects are equal if they are: 1. the same object or 2. have the same value (when it's meaningful). In both cases this can be accomplished pretty easily: You can do it with a try..except block, and you can write the try...except block inside the __contains__ method. (It's really pretty simple: try: return a == b except TypeError: return a is b ) Also, Mike said that you'll need an idlist object too - and I think he's right and that there's nothing wrong with it. Note that while you can easily define the current == behaviour using the proposed behaviour, you can't define the proposed behaviour using the current behaviour. Also note that using the current behaviour, you can't easily treat objects that do define a meaningful value comparison, by identity. Also note that in the cases that you do want identity-based behaviour, defining it explicitly can result in a more efficient program: explicit identity-based dict doesn't have to call any __hash__ and __eq__ protocols - it can compare the pointers themselves. The same if you want to locate a specific object in a list - use the proposed idlist and save yourself O(n) value-based comparisons, which might be heavy. Noam -- http://mail.python.org/mailman/listinfo/python-list
ANN: byteplay - a bytecode assembler/disassembler
Hello, I would like to present a module that I have wrote, called byteplay. It's a Python bytecode assembler/disassembler, which means that you can take Python code object, disassemble them into equivalent objects which are easy to play with, play with them, and then assemble a new, modified, code object. I think it's pretty useful if you like to learn more about Python's bytecode - playing with things and seeing what happens is a nice way to learn, I think. Here's a quick example. We can define this stupid function: >>> def f(a, b): ... print (a, b) >>> f(3, 5) (3, 5) We can convert it to an equivalent object, and see how it stores the byte code: >>> from byteplay import * >>> c = Code.from_code(f.func_code) >>> from pprint import pprint; pprint(c.code) [(SetLineno, 2), (LOAD_FAST, 'a'), (LOAD_FAST, 'b'), (BUILD_TUPLE, 2), (PRINT_ITEM, None), (PRINT_NEWLINE, None), (LOAD_CONST, None), (RETURN_VALUE, None)] We can change the bytecode easily, and see what happens. Let's insert a ROT_TWO opcode, that will swap the two arguments: >>> c.code[3:3] = [(ROT_TWO, None)] >>> f.func_code = c.to_code() >>> f(3, 5) (5, 3) You can download byteplay from http://byteplay.googlecode.com/svn/trunk/byteplay.py and you can read (and edit) the documentation at http://wiki.python.org/moin/ByteplayDoc . I will be happy to hear if you find it useful, or if you have any comments or ideas. Have a good day, Noam Raphael -- http://mail.python.org/mailman/listinfo/python-list
Allowing zero-dimensional subscripts
Hello, I discovered that I needed a small change to the Python grammar. I would like to hear what you think about it. In two lines: Currently, the expression "x[]" is a syntax error. I suggest that it will be evaluated like "x[()]", just as "x[a, b]" is evaluated like "x[(a, b)]" right now. In a few more words: Currently, an object can be subscripted by a few elements, separated by commas. It is evaluated as if the object was subscripted by a tuple containing those elements. I suggest that an object will also be subscriptable with no elements at all, and it will be evaluated as if the object was subscripted by an empty tuple. It involves no backwards incompatibilities, since we are dealing with the legalization of a currently illegal syntax. It is consistent with the current syntax. Consider that these identities currently hold: x[i, j, k] <--> x[(i, j, k)] x[i, j] <--> x[(i, j)] x[i, ] <--> x[(i, )] x[i] <--> x[(i)] I suggest that the next identity will hold too: x[] <--> x[()] I need this in order to be able to refer to zero-dimensional arrays nicely. In NumPy, you can have arrays with a different number of dimensions. In order to refer to a value in a two-dimensional array, you write a[i, j]. In order to refer to a value in a one-dimensional array, you write a[i]. You can also have a zero-dimensional array, which holds a single value (a scalar). To refer to its value, you currently need to write a[()], which is unexpected - the user may not even know that when he writes a[i, j] he constructs a tuple, so he won't guess the a[()] syntax. If my suggestion is accepted, he will be able to write a[] in order to refer to the value, as expected. It will even work without changing the NumPy package at all! In the normal use of NumPy, you usually don't encounter zero-dimensional arrays. However, I'm designing another library for managing multi-dimensional arrays of data. Its purpose is similiar to that of a spreadsheet - analyze data and preserve the relations between a source of a calculation and its destination. In such an environment you may have a lot of multi-dimensional arrays - for example, the sales of several products over several time periods. But you may also have a lot of zero-dimensional arrays, that is, single values - for example, the income tax. I want the access to the zero-dimensional arrays to be consistent with the access to the multi-dimensional arrays. Just using the name of the zero-dimensional array to obtain its value isn't going to work - the array and the value it contains have to be distinguished. I have tried to change CPython to support it, and it was fairly easy. You can see the diff against the current SVN here: http://python.pastebin.com/768317 The test suite passes without changes, as expected. I didn't include diffs of autogenerated files. I know almost nothing about the AST, so I would appreciate it if someone who is familiar with the AST will check to see if I did it right. It does seem to work, though. Well, what do you think about this? Have a good day, Noam Raphael -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Terry Reedy wrote: > > In a few more words: Currently, an object can be subscripted by a few > > elements, separated by commas. It is evaluated as if the object was > > subscripted by a tuple containing those elements. > > It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted by a > tuple. > Adding () around the non-empty tuple adds nothing except a bit of noise. > It doesn't necessarily matter, but technically, it is not "a tuple". The "1, 2" in "x[1, 2]" isn't evaluated according to the same rules as in "x = 1, 2" - for example, you can have "x[1, 2:3:4, ..., 5]", which isn't a legal tuple outside of square braces - in fact, it even isn't legal inside parens: "x[(1, 2:3:4, ..., 5)]" isn't legal syntax. Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Terry Reedy wrote: > So I do not see any point or usefulness in saying that a tuple subcript is > not what it is. I know that a tuple is *constructed*. The question is, is this, conceptually, the feature that allows you to ommit the parentheses of a tuple in some cases. If we see this as the same feature, it's reasonable that "nothing" won't be seen as an empty tuple, just like "a = " doesn't mean "a = ()". However, if we see this as a different feature, which allows multidimensional subscript by constructing a tuple behind the scenes, constructing an empty tuple for x[] seems very reasonable to me. Since in some cases you can't have the parentheses at all, I think that x[] makes sense. Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Sybren Stuvel wrote: > I think it's ugly to begin with. In math, one would write simply 'x' > to denote an unsubscribed (ubsubscripted?) 'x'. And another point, why > would one call __getitem__ without an item to call? I think that in this case, mathematical notation is different from python concepts. If I create a zero-dimensional array, with the value 5, like this: >>> a = array(5) I refer to the array object as "a", and to the int it stores as "a[]". For example, I can change the value it holds by writing >>> a[] = 8 Writing "a = 8" would have a completely different meaning - create a new name, a, pointing at a new int, 8. Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello, Fredrik Lundh wrote: > (but should it really result in an empty tuple? wouldn't None be a bit > more Pythonic?) I don't think it would. First of all, x[()] already has the desired meaning in numpy. But I think it's the right thing - if you think of what's inside the brackets as a list of subscripts, one for each dimension, which is translated to a call to __getitem__ or __setitem__ with a tuple of objects representing the subscripts, then an empty tuple is what you want to represent no subscripts. Of course, one item without a comma doesn't make a tuple, but I see this as the special case - just like parentheses with any number of commas are interpreted as tuples, except for parentheses with one item without a comma. (By the way, thanks for the tips for posting a PEP - I'll try to do it quickly.) Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Hello,
Following Fredrik's suggestion, I wrote a pre-PEP. It's available on
the wiki, at http://wiki.python.org/moin/EmptySubscriptListPEP and I
also copied it to this message.
Have a good day,
Noam
PEP: XXX
Title: Allow Empty Subscript List Without Parentheses
Version: $Revision$
Last-Modified: $Date$
Author: Noam Raphael <[EMAIL PROTECTED]>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 09-Jun-2006
Python-Version: 2.5?
Post-History: 30-Aug-2002
Abstract
This PEP suggests to allow the use of an empty subscript list, for
example ``x[]``, which is currently a syntax error. It is suggested
that in such a case, an empty tuple will be passed as an argument to
the __getitem__ and __setitem__ methods. This is consistent with the
current behaviour of passing a tuple with n elements to those methods
when a subscript list of length n is used, if it includes a comma.
Specification
=
The Python grammar specifies that inside the square brackets trailing
an expression, a list of "subscripts", separated by commas, should be
given. If the list consists of a single subscript without a trailing
comma, a single object (an ellipsis, a slice or any other object) is
passed to the resulting __getitem__ or __setitem__ call. If the list
consists of many subscripts, or of a single subscript with a trailing
comma, a tuple is passed to the resulting __getitem__ or __setitem__
call, with an item for each subscript.
Here is the formal definition of the grammar:
::
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
This PEP suggests to allow an empty subscript list, with nothing
inside the square brackets. It will result in passing an empty tuple
to the resulting __getitem__ or __setitem__ call.
The change in the grammar is to make "subscriptlist" in the first
quoted line optional:
::
trailer: '(' [arglist] ')' | '[' [subscriptlist] ']' | '.' NAME
Motivation
==
This suggestion allows you to refer to zero-dimensional arrays
elegantly. In
NumPy, you can have arrays with a different number of dimensions. In
order to refer to a value in a two-dimensional array, you write
``a[i, j]``. In order to refer to a value in a one-dimensional array,
you write ``a[i]``. You can also have a zero-dimensional array, which
holds a single value (a scalar). To refer to its value, you currently
need to write ``a[()]``, which is unexpected - the user may not even
know that when he writes ``a[i, j]`` he constructs a tuple, so he
won't guess the ``a[()]`` syntax. If the suggestion is accepted, the
user will be able to write ``a[]`` in order to refer to the value, as
expected. It will even work without changing the NumPy package at all!
In the normal use of NumPy, you usually don't encounter
zero-dimensional arrays. However, the author of this PEP is designing
another library for managing multi-dimensional arrays of data. Its
purpose is similar to that of a spreadsheet - to analyze data and
preserve the relations between a source of a calculation and its
destination. In such an environment you may have many
multi-dimensional arrays - for example, the sales of several products
over several time periods. But you may also have several
zero-dimensional arrays, that is, single values - for example, the
income tax rate. It is desired that the access to the zero-dimensional
arrays will be consistent with the access to the multi-dimensional
arrays. Just using the name of the zero-dimensional array to obtain
its value isn't going to work - the array and the value it contains
have to be distinguished.
Rationale
=
Passing an empty tuple to the __getitem__ or __setitem__ call was
chosen because it is consistent with passing a tuple of n elements
when a subscript list of n elements is used. Also, it will make NumPy
and similar packages work as expected for zero-dimensional arrays
without
any changes.
Another hint for consistency: Currently, these equivalences hold:
::
x[i, j, k] <--> x[(i, j, k)]
x[i, j] <--> x[(i, j)]
x[i, ] <--> x[(i, )]
x[i]<--> x[(i)]
If this PEP is accepted, another equivalence will hold:
::
x[] <--> x[()]
Backwards Compatibility
===
This change is fully backwards compatible, since it only assigns a
meaning to a previously illegal syntax.
Reference Implementation
Available as SF Patch no. 1503556.
(and also in http://python.pastebin.com/768317 )
It passes the Python test suite, but currently doesn't provide
additional tests or documentation.
Copyright
=
This document has been placed in the public domain.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
George Sakkis wrote: > [EMAIL PROTECTED] wrote: > > > However, I'm designing another library for > > managing multi-dimensional arrays of data. Its purpose is similiar to > > that of a spreadsheet - analyze data and preserve the relations between > > a source of a calculation and its destination. > > Sounds interesting. Will it be related at all to OLAP or the > Multi-Dimensional eXpressions language > (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? > Thanks for the reference! I didn't know about any of these. It will probably be interesting to learn from them. From a brief look at OLAP in wikipedia, it may have similarities to OLAP. I don't think it will be related to Microsoft's language, because the language will simply by Python, hopefully making it very easy to do whatever you like with the data. I posted to python-dev a message that (hopefully) better explains my use for x[]. Here it is - I think that it also gives an idea on how it will look like. I'm talking about something similar to a spreadsheet in that it saves data, calculation results, and the way to produce the results. However, it is not similar to a spreadsheet in that the data isn't saved in an infinite two-dimensional array with numerical indices. Instead, the data is saved in a few "tables", each storing a different kind of data. The tables may be with any desired number of dimensions, and are indexed by meaningful indices, instead of by natural numbers. For example, you may have a table called sales_data. It will store the sales data in years from set([2003, 2004, 2005]), for car models from set(['Subaru', 'Toyota', 'Ford']), for cities from set(['Jerusalem', 'Tel Aviv', 'Haifa']). To refer to the sales of Ford in Haifa in 2004, you will simply write: sales_data[2004, 'Ford', 'Haifa']. If the table is a source of data (that is, not calculated), you will be able to set values by writing: sales_data[2004, 'Ford', 'Haifa'] = 1500. Tables may be computed tables. For example, you may have a table which holds for each year the total sales in that year, with the income tax subtracted. It may be defined by a function like this: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate) Now, like in a spreadsheet, the function is kept, so that if you change the data, the result will be automatically recalculated. So, if you discovered a mistake in your data, you will be able to write: sales_data[2004, 'Ford', 'Haifa'] = 2000 and total_sales[2004] will be automatically recalculated. Now, note that the total_sales table depends also on the income_tax_rate. This is a variable, just like sales_data. Unlike sales_data, it's a single value. We should be able to change it, with the result of all the cells of the total_sales table recalculated. But how will we do it? We can write income_tax_rate = 0.18 but it will have a completely different meaning. The way to make the income_tax_rate changeable is to think of it as a 0-dimensional table. It makes sense: sales_data depends on 3 parameters (year, model, city), total_sales depends on 1 parameter (year), and income_tax_rate depends on 0 parameters. That's the only difference. So, thinking of it like this, we will simply write: income_tax_rate[] = 0.18 Now the system can know that the income tax rate has changed, and recalculate what's needed. We will also have to change the previous function a tiny bit, to: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate[]) But it's fine - it just makes it clearer that income_tax_rate[] is a part of the model that may change its value. Have a good day, Noam -- http://mail.python.org/mailman/listinfo/python-list
How can I know how much to read from a subprocess
Hello, I want to write a terminal program in pygtk. It will run a subprocess, display everything it writes in its standard output and standard error, and let the user write text into its standard input. The question is, how can I know if the process wrote something to its output, and how much it wrote? I can't just call read(), since it will block my process. Thanks, Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I know how much to read from a subprocess
Ok, I could have researched this before posting, but here's an explanation how to do it with twisted: http://unpythonic.blogspot.com/2007/08/spawning-subprocess-with-pygtk-using.html It seems that another solution is gobject.io_add_watch, but I don't see how it tells me how much I can read from the file - if I don't know that, I won't know the argument to give to the read() method in order to get all the data: http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--io-add-watch Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I know how much to read from a subprocess
On Sep 18, 1:48 pm, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote: > On 2007-09-17, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > It seems that another solution is gobject.io_add_watch, but I don't > > see how it tells me how much I can read from the file - if I don't > > know that, I won't know the argument to give to the read() method in > > order to get all the data: > > >http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-g... > > Usually, gobject only tells you that data is there (that is all it knows). > Therefore a read(1) should be safe. But even if it's fast enough, how do you know how many times you should call read(1)? If you do it too much, you'll be blocked until more output is available. > If that is too slow, consider os.read() which reads all data available (afaik, > never tried it myself). > I tried it now, and it blocks just like the normal file.read(). Thanks, Noam -- http://mail.python.org/mailman/listinfo/python-list
audio on os x using python, mad, ao
this message was originally posted by someone else and closed without a
proper answer. i'm reposting it in hopes that someone will provide a
solution.
Begin Quote:
"I'm attempting to play an mp3 file on OSX, but am running into some
difficulty. When using py-mad and py-ao, I only get static with the
following code (which is derived off another mailing that I found from
this list's archives):
#!/usr/bin/env python
'''Requires:
py-mad (mp3 ability)
py-ao (system audio ability)
'''
import mad, ao, sys
mf = mad.MadFile(sys.argv[1])
dev = ao.AudioDevice('macosx')#osx device, linux: use "oss" or "alsa"
while 1:
buf = mf.read()
if buf is None:
break
dev.play(buf, len(buf))
Does anyone know why this produces static, or whether there's a better
method of producing audio output that's also cross-platform (OSX,
linux)? I've looked at pymedia, but they do not support OSX at the
moment.
Thanks!"
--
http://mail.python.org/mailman/listinfo/python-list
Making Line Graphs
I'm looking for an easy way to display simple line graphs generated by a python program in Windows. It could be done from within the program, or I could write the information out to a file and call an external program. Either is fine. Does anybody have any recommendations for a good program from generating these simple graphs? -- http://mail.python.org/mailman/listinfo/python-list
Question on multiple Python users in one application
Hello. Please pardon a newbie question. I have a Windows multi-user program that can be used by an arbitrary number of users at once. They can work independently, or they can share data at the file or even variable level if they want. I want to give them the ability to write Python programs within this environment. So I intend to embed CPython access in the program. The basic embedding of CPython seems straight forward. But since I have multiple users, each needs their own Python sandbox, so if they all compile programs with variable 'spam', it doesn't collide. Of course they can all have different programs running at the same time too. I think I need to do some behind-the-scenes thread management and possibly namespace management to allow this to work correctly. But this is where I'm confused, and not sure where to start. I know how to tell my users apart. The program is multi-threaded, but there is not a direct correspondence between a user and a thread; a single user can switch threads, but I know when this happens. Can someone please suggest what I should be looking at and doing to be able to effectively run multiple independent Pythons in a single program? Thank you for your help! Loren -- https://mail.python.org/mailman/listinfo/python-list
pyqt drop to open a file
Hi, anyone can give a simple example or a link on how to use 'drop' with pyqt. what I'm looking for is drop a file to main widget then program get the path\filename something like: main_widget set to accept 'drop event', set filename when 'drop event happens' then the filename is path\filename of the file user drag from any location to main widget. Thanks for any help. -Ray -- http://mail.python.org/mailman/listinfo/python-list
Python component model
The definition of a component model I use below is a class which allows properties, methods, and events in a structured way which can be recognized, usually through some form of introspection outside of that class. This structured way allows visual tools to host components, and allows programmers to build applications and libraries visually in a RAD environment. The Java language has JavaBeans as its component model which allows Java applications to be built in a visual RAD way. Microsoft's .Net has a component model built-in to its .Net class libraries as well as supported by CLR which allows .Net applications to be built visually using components created in any .Net supported language. With Python things are different. There is no single component model which allows Python developers to build components which will be used and recognized by the various RAD Python tools on the market. Instead a developer must create a slightly different set of Python classes for each RAD Python tool. This is the situation despite Python's having easily as much functionality, if not much more, as Java or .Net languages such as C#, VB, or C++/CLI for creating components, and for allowing visual tools to introspect the properties, methods, and events of Python classes. I believe that Python should have a common components model for all RAD development environments, as that would allow the Python programmer to create a set of classes representing components which would work in any environment. I want to immediately point out that components do not simply mean visual GUI components but what may be even more important, non-visual components. Having used RAD development environments to create applications, I have found such environments almost always much better than coding complex interactions manually, and I believe that visual development environments are almost a necessity in today's world of large-scale, multi-tier, and enterprise applications. Has there ever been, or is there presently anybody, in the Python developer community who sees the same need and is working toward that goal of a common component model in Python, blessed and encouraged by those who maintain the Python language and standard modules themselves ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
[EMAIL PROTECTED] wrote: > Edward> The definition of a component model I use below is a class which > Edward> allows properties, methods, and events in a structured way which > Edward> can be recognized, usually through some form of introspection > Edward> outside of that class. This structured way allows visual tools > Edward> to host components, and allows programmers to build applications > Edward> and libraries visually in a RAD environment. > > ... > Edward> I believe that Python should have a common components model for > Edward> all RAD development environments, as that would allow the Python > Edward> programmer to create a set of classes representing components > Edward> which would work in any environment. > > Having never used java or .NET I'm not sure what you're looking for. Does > Python's current introspection not work? Is it someone too unstructured > (whatever "structured" means)? Can you give a simple example? In the typical RAD development environment, a particular component model allows one to drop components, which are classes corresponding to a particular inner representation which tells the development environment what are the "properties" and "events" of that component, and subsequently set "properties" for that component and add handlers for its "events" visually. Subsequently When the components are instantiated at run-time, the particular "properties" are automagically set and the particular "events" are automagically tied to event handlers in other classes ( usually a window, or form, although it can be in any other class which can handle events ). How this "automagically" is done depends on the visual development environment. I find it very neat that I, the end-user of the component, does not have to write the boiler-plate code to set "properties" and hook up "events" and can do this visually. I realize that others may find this unimportant. But in a visual environment where not only non-viusual components are involved, but also visual GUI components are, this also allows the visual look of a particular window ( form or screen if you like ) to be composed automatically. At the same time hooking non-visual components automagically at design time so that they are connected at run-time to event handlers is also very nice. In order to make such a system work, the visual RAD environment needs to know what in a class makes it a component, and what in that components specifies the "properties" and "events" for which it will automagically setup the correct "code" which works at run-time. Without a component model to tell it these things, it can not work to produce the boiler-plate code necessary to set "properties" and hook event handlers to an event. In JavaBeans, for Java, and the System.ComponentModel namespace, as well as properties, delegates, and events in .Net, there exists a common component model which defines, in these environments, what a components is so that the visual RAD development can do its magic. I realize that many Python programmers don't see the necessity for having a RAD visual devlopment environment doing for them what they can do by hand in their Python code, particularly in the constructor to classes. But there are people who have used such a RAD model, particularly when setting up a GUI application or Web application, who appreciate the ease of use of such a RAD visual environment, especially in the area of dropping visual controls on a window and having that window appear at run-time with the particular look which they have visually setup at design time. But even beyond the more common visual setup of a window or web page, a visual RAD environment allows the end-user programmer to visually create boiler-plate code for setting the "properties" and "events" of non-visual classes, which make up the greater part of the internal logic of any given program. More importantly a common component model, which works in any language's visual RAD environment, enables the development and re-use of components which are as easily used as dropping that component from a component palette onto a visual container, usually a representation of a run-time window, and setting it's "properties" and/or "events". The visual manipulation of components does not preclude making manipulations at run-time through code also if necessary, and all visual environements allow the setting of "properties" and "events" at run-time also in the usual way. If one has used Borland's Delphi or C++ Builder IDEs, or Sun's NetBeans or IBM's Eclipse for Java, or Microsoft's Visual Studio for .Net, one knows what I mean as far as a visual RAD environment. All of these are made possible by a common component model which different development environments can use. There's nothing wrong with Python's introspection. In fact Python's facilities in this area and its support for metadata are stronger than
Re: Python component model
Echo wrote: > On 10/9/06, Edward Diener No Spam <[EMAIL PROTECTED]> > wrote: >> The definition of a component model I use below is a class which allows >> properties, methods, and events in a structured way which can be >> recognized, usually through some form of introspection outside of that >> class. This structured way allows visual tools to host components, and >> allows programmers to build applications and libraries visually in a RAD >> environment. >> >> The Java language has JavaBeans as its component model which allows Java >> applications to be built in a visual RAD way. Microsoft's .Net has a >> component model built-in to its .Net class libraries as well as >> supported by CLR which allows .Net applications to be built visually >> using components created in any .Net supported language. >> >> With Python things are different. There is no single component model >> which allows Python developers to build components which will be used >> and recognized by the various RAD Python tools on the market. Instead a >> developer must create a slightly different set of Python classes for >> each RAD Python tool. This is the situation despite Python's having >> easily as much functionality, if not much more, as Java or .Net >> languages such as C#, VB, or C++/CLI for creating components, and for >> allowing visual tools to introspect the properties, methods, and events >> of Python classes. >> >> I believe that Python should have a common components model for all RAD >> development environments, as that would allow the Python programmer to >> create a set of classes representing components which would work in any >> environment. I want to immediately point out that components do not >> simply mean visual GUI components but what may be even more important, >> non-visual components. Having used RAD development environments to >> create applications, I have found such environments almost always much >> better than coding complex interactions manually, and I believe that >> visual development environments are almost a necessity in today's world >> of large-scale, multi-tier, and enterprise applications. >> >> Has there ever been, or is there presently anybody, in the Python >> developer community who sees the same need and is working toward that >> goal of a common component model in Python, blessed and encouraged by >> those who maintain the Python language and standard modules themselves ? >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > If you are talking about about creating a GUI and having be able to > run using different GUI libraries like Tkinter, wxPython, wxgtk, ect. > You could look into Dabo(http://dabodev.com/). It is designed so that > you can design your GUI and have it run with what ever GUI library you > want(only wxPython is supported at the moment. And I think that > Tkinter works somewhat.) It's not just for GUI controls that a component model exists in the other environments I mentioned. Non-GUI components are intrinsically as important, if not more so, to a component model architecture. Also, quite honestly, I think a component model would have to be specified by the core Python developers instead of retrofitted against the popular GUI environments for Python which currently exist. Also I admit I am no fan of wx-you-name-it, whose "event" model especially I find way too limiting and ineffective in relation to the entire area of component-based programming and events. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Chaz Ginger wrote: > Edward Diener No Spam wrote: >> [EMAIL PROTECTED] wrote: >>> Edward> The definition of a component model I use below is a class >>> which >>> Edward> allows properties, methods, and events in a structured way >>> which >>> Edward> can be recognized, usually through some form of introspection >>> Edward> outside of that class. This structured way allows visual >>> tools >>> Edward> to host components, and allows programmers to build >>> applications >>> Edward> and libraries visually in a RAD environment. >>> >>> ... >>> Edward> I believe that Python should have a common components >>> model for >>> Edward> all RAD development environments, as that would allow the >>> Python >>> Edward> programmer to create a set of classes representing components >>> Edward> which would work in any environment. >>> >>> Having never used java or .NET I'm not sure what you're looking for. >>> Does >>> Python's current introspection not work? Is it someone too unstructured >>> (whatever "structured" means)? Can you give a simple example? >> In the typical RAD development environment, a particular component model >> allows one to drop components, which are classes corresponding to a >> particular inner representation which tells the development environment >> what are the "properties" and "events" of that component, and >> subsequently set "properties" for that component and add handlers for >> its "events" visually. snip... >> > > Why not propose something. That is the easiest way to get things moving. How does one do that ? Propose something here on this NG or is there some other official way ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Robert Kern wrote: > Edward Diener No Spam wrote: > >> There's nothing wrong with Python's introspection. In fact Python's >> facilities in this area and its support for metadata are stronger than >> any of these other languages ! However there is no common component >> model which specifies that X is a "property" or Y is an "event" of a >> Python class which can be visually manipulated at design-time and >> automagically set at run-time, so that any given Python RAD visual >> environment will treat a Python class, specified as a component, in >> exactly the same way. Also in these other languages, a component is >> different from a class in that a component is recognized in a >> particular way, often so that the component can interact if necessary >> with its container and/or visual site. > > You'll definitely want to take a look at Enthought's Traits (disclaimer: > I work for Enthought). I'm supposed to be on vacation now, so I'm not > going to give you the full rundown of Traits and Traits UI, so I'm > simply going to point you to the page we have about it: > > http://code.enthought.com/traits/ It looks as if traits is an attempt to create a "property" in the component terminology which I originally specified. I will take a look at it. > > You can talk to the rest of the Enthought crew on the enthought-dev > mailing list if you have any questions: > > https://mail.enthought.com/mailman/listinfo/enthought-dev Already subscribed. Thanks ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
goon wrote: >> or IBM's Eclipse for Java > > Or Eclipse for Python using PyDev? [0] Those are very nice features but there is no re-usable Python bean support like there is a Java bean. That was my initial point. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Michael wrote: > Edward Diener No Spam wrote: > >> Has there ever been, or is there presently anybody, in the Python >> developer community who sees the same need and is working toward that >> goal of a common component model in Python, blessed and encouraged by >> those who maintain the Python language and standard modules themselves ? > > Someone aiming towards a standard to /replace/ everyone else's? That > presupposes a level of arrogance that seems unusual in the python world. > (whilst everyone's proud of their own code and they _generally_ respect > other people's even if it's not their cup of tea). The reason I would like to see a standard component model for Python is so 3rd party developers could create their classes to conform to this model and work in any RAD IDE environment which adapts it. That's the way JavaBeans work, that the way Borland's VCL component model works, and that's the way .Net works. When there are many different component models, the 3rd party developer must adapt their components to each model for a particular environment. But far be it from me to want to replace everybody else's model . By your reasoning above, standardizing anything in software is an arrogant proposition. Whereas I look at standardization, when it is well done, as a boon to programmers. > > The WSGI standard could be a form of component model, and has gone through > the PEP process so that might match your criterion. I do not know what it is but I will look it up. > As for component > models, they do exist. > > Our component model on the Kamaelia project [1] is one that's heavily > designed around the idea of composition and independent execution of > components and message passing (message passing maps to events for some > sorts of message), >[1] http://kamaelia.sourceforge.net/Home I will look at kamaelia. Thanks ! > > I wouldn't think of proposing it as the single standard to rule them all > though, for the simple reason every approach has its own strengths. (We do > find the approach extremely useful though) > > If you want a quick example of the core ideas, a tutorial aimed around > building a massively simplified core is here: >http://kamaelia.sourceforge.net/MiniAxon/ > > If you want to see a substantial example, you can look here: >* http://tinyurl.com/oqjfb - whiteboarding with audio where every client > is a server. The entire resulting system is also a component. > > For something more simplistic: >* http://kamaelia.sourceforge.net/Examples/SimplestPresentationTool.html > > Something halfway in terms of complexity (a PVR for transcoding everything > broadcast on digital TV): >* http://tinyurl.com/lvygq > (OK, you need to add more channels, but you'd need more CPU's too) > > We also have tools for introspecting a running system, and also a visual > composition tool (called Compose) [2] for creating simple systems > graphically, and that, as you say, handles a significant chunk of > dreariness. Suggestions on improving the model and composition tool are > very welcome, code is even more welcome :) > >[2] Sample system created with the newest version of Compose: > http://tinyurl.com/numwk >Compose is also a Kamaelia system, and can be found here: > http://tinyurl.com/p7z76 >(bulk of the wiring up is in the bottom of the file - this is an >interesting example because of the use of Pygame and Tk for different >parts of the interface where appropriate) > > > However, off the top of my head, you should also look at Zope's component > model, Trac's component model, Twisted's model & PEAK, and any proposal > to say "this is the solution", needs to be compelling for all of these > projects. A standard component model could be used as a base for other more advanced needs. Most of those mentioned above seem to involve web application frameworks whereas my idea of a component model just assumes the paradigms of properties, methods, and events which may allow re-usable components at a base level in any environment. A particular implementation is certainly allowed to build a more complicated idea of a component, through inheritance, from a base level component, and this is in fact the way that most components work in current component model environments I have mentioned. For instance in .Net a control is a component with other added qualities. So while one could build components which are not controls, it is necessary to add functionality to the base level idea of a component in order to create a control. > > Note, they do change where there's a benefit - twisted adopted some > int
Re: Python component model
Nick Vatamaniuc wrote: > Edward Diener No Spam wrote: >> Michael wrote: > > Python does not _need_ a component model just as you don't _need_ a RAD > IDE tool to write Python code. The reason for having a component model > or a RAD IDE tool is to avoid writing a lot of boiler plate code. > Python is terse enough that boiler plate code is not needed, just type > what you need into an editor. It seems that you talk about Python but > you are still thinking in Java or C++. A RAD IDE tool to hook up components into an application or library ( module in Python ) has nothing to do with terseness and everything to do with ease of programming. All you are saying is that you don't have a need for this, but perhaps others do. I don't mind others saying they have no need or seeing no benefit. But if you have ever used a visual design-time environment for creating applications you might feel differently. "Thinking in Java or C++" as opposed to Python does not mean anything to me as a general statement. I am well aware of the difference between statically and dynamically typed languages but why this should have anything to do with RAD programming is beyond me. Do you care to elucidate this distinction ? > > At the same time one could claim that Python already has certain > policies that makes it seem as if it has a component model. Take a look > at the "magic methods". For example if a class has a __len__ method, it > is possible to use the len() function on an instance of that class. If > a class has the __getitem__ then indexing can be used on that class's > insance. Then Python has properties (see > http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html). Just by > inspecting the object one can tell a great deal about them (even read > the documentation if needed, by using the __doc__ attribute). What > other standards would you propose for the core language? Python has great facilities for a component model, much better than the other languages I use regularly ( C++, C#, Java ). I am not arguing against that. A component model for RAD tools allows the tool to expose properties and events to the end-user at design time so that at run-time the properties and events are automatically setup once an object is instantiated. The essence of a component model for RAD programming is how one specifies properties and events for a class to be manipulated by the RAD tool at design time. Another obvious part of the component model is how one specifies that the properties and events one sets up at design-time are serialized so that at run-time they are properly set. A final element of a component model is the ability of a component to interact with the environment in which it exists at design time, through property editors, and at run-time, the latter being obviously more important for visual controls than non-visual components. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Paul Rubin wrote: > "Nick Vatamaniuc" <[EMAIL PROTECTED]> writes: >> Python does not _need_ a component model just as you don't _need_ a RAD >> IDE tool to write Python code. The reason for having a component model >> or a RAD IDE tool is to avoid writing a lot of boiler plate code. > > It's also so that applications written in differing languages can call > each other. That's a possible reason, but with JavaBeans and EJBs for Java there is just a single language and I am sure there are many Java programmers who enjoy using Eclipse, NetBeans, or JBuilder to name a few RAD IDEs which allow them to create their applications using a design-time visual environment. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Diez B. Roggisch wrote: > Paul Rubin schrieb: >> "Nick Vatamaniuc" <[EMAIL PROTECTED]> writes: >>> Python does not _need_ a component model just as you don't _need_ a RAD >>> IDE tool to write Python code. The reason for having a component model >>> or a RAD IDE tool is to avoid writing a lot of boiler plate code. >> >> It's also so that applications written in differing languages can call >> each other. > > Nope. Things like CORBA and COM do have that property, but e.g. the Java > beans spec has only a meaning inside the VM. Not sure about .NET, but I > can imagine there it's the same thing. > > All the languages he mentioned are statically typed, or the component > models themselves are. So the component model is basically needed (as > others also mentioned) to glue things together, to dynamize that - > whereas python is dynamic on the first hand, and actually lacks static > typing to infer component properties... While I understand dynamic typing, I still think it is possible to create attributes in a Python component model which could tell a RAD tool what type the attribute will encompass for the purpose of properties and events. Obviously a "name, type" tuple, among other possible information would have to be used. But given Python's amazingly flexible type and introspection system, this should be possible. Of course I am not trying to change the nature of normal Python attributes per se at all, and one of the most important things in a property-method-event component model is to be able to specify properties that are distinct from just normal object data members. So one of the most important things in a Python component model would be the ability to tag component properties as totally distinct from normal Python class attributes or property attributes. Given that Python already has new-style class properties, maybe another name for the component properties I envision is needed to avoid confusion. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Steve Holden wrote: > Diez B. Roggisch wrote: > [...] >>> Just the same, one can use IronPython to call components written in >>> other languages. And, I believe, vice versa. >> >> >> Sure, as I can do it in jython. But the key point is: can your ordinary >> python-object be published as a component? At least for jython I can >> say "no", you will have to subclass an already existing >> java-object/interface. And I have difficulties imagining that it is any >> different in .NET - because I've read statements that claimed that the >> structure of the VM/runtime is orientied towards single-inheritance >> statically typed languages as C#/java. >> > The answer to this question is currently beyond me. Maybe someone who > knows more about IronPython can elucidate. I do know (as you probably do > also) that Python generates code for the .NET CLR, however. I am not sure about current IronPython functionality but the end result is that one should be able to create .Net components and classes using Python with IronPython just as one does in C#, C++/CLI, or VB .NET. But this is not creating a component model for Python except in the .Net environment, which essentially means Windows unless IronPython will work under Mono, and Microsoft does not kill Mono. I don't think all those "ifs" is something a Python programmer wants to deal with in possible RAD component development. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Fredrik Lundh wrote: > Nick Vatamaniuc wrote: > >> At the same time one could claim that Python already has certain >> policies that makes it seem as if it has a component model. > > every Python object surely qualifies as a component, for any non-myopic > definition of that word, and everything inside a Python program is an > object. so yes, Python has a component model, and Python programmers > are using that model all over the place. > > what might be missing is support for publishing additional metadata > using a standardized vocabulary, and a way to access that data with- > out having to actually create the object. > > implementing this using existing mechanisms is trivial (as the endless > stream of interface/component/adapter/trait implementations have shown > us); coming up with a good-enough-to-be-useful-for-enough-people > vocabulary is a lot harder. There's no doubt that Python's excellent introspection mechanism allows an outside RAD-like tool to inspect the workings of any Python object. But that does not make it a component model in my original use of the term on this thread. A RAD tool needs to know what properties and events within a class can be manipulated visually, and it needs to be able to serialize those properties and events so that they are set at run-time automatically once an object is created. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Michael Sparks wrote: > Edward Diener No Spam wrote: >> Michael wrote: >>> Edward Diener No Spam wrote: >>> >>>> Has there ever been, or is there presently anybody, in the Python >>>> developer community who sees the same need and is working toward that >>>> goal of a common component model in Python, blessed and encouraged by >>>> those who maintain the Python language and standard modules themselves ? >>> Someone aiming towards a standard to /replace/ everyone else's? That >>> presupposes a level of arrogance that seems unusual in the python world. >>> (whilst everyone's proud of their own code and they _generally_ respect >>> other people's even if it's not their cup of tea). >> The reason I would like to see a standard component model for Python is >> so 3rd party developers could create their classes to conform to this >> model and work in any RAD IDE environment which adapts it. That's the >> way JavaBeans work, that the way Borland's VCL component model works, >> and that's the way .Net works. When there are many different component >> models, the 3rd party developer must adapt their components to each >> model for a particular environment. >> >> But far be it from me to want to replace everybody else's model . > > Well that's the thing you *do* want since you want the previous > paragraph ;-) > (Or at least a way to adapt component models.) I was being funny above. Yes I would like to establish a basic component model for RAD development in Python. But surely it need not replace all others but could serve at least as a base class for other derived models for various environments. That way a developer writing a Python component could have it work in these environments as a simple component and more complex components, tailored to that environment could be created as necessary through inheritance. > >> By your reasoning above, standardizing anything in software is an >> arrogant proposition. Whereas I look at standardization, when it is well >> done, as a boon to programmers. > > OK, maybe I was being a bit strong - I was merely thinking "lots of > people have something like this already, and I've not seen anyone push > their model as THE model", (even if lots of people like *their* model > :-) > > However, I was also being a bit tongue in cheek, though I should have > said unreasonable, not arrogant: >"...all progress depends on the unreasonable man." -- Bernard Shaw. Bravo, Shaw. Of course by unreasonable I assume Shaw meant those using imagination and inspiration along with logic and reason. > > What could have some mileage though is proposing a standard way for > these component models to interoperate. What that would look like > (given the wildly different models :), is another matter and an > exercise for the interested reader ;-) > >>> The WSGI standard could be a form of component model, and has gone through >>> the PEP process so that might match your criterion. >> I do not know what it is but I will look it up. > > NB, I'm using component model in it's loosest form there. > >>> As for component >>> models, they do exist. >>> >>> Our component model on the Kamaelia project [1] is one that's heavily >>> designed around the idea of composition and independent execution of >>> components and message passing (message passing maps to events for some >>> sorts of message), >>>[1] http://kamaelia.sourceforge.net/Home >> I will look at kamaelia. Thanks ! > > You're welcome. Any deficiencies or improvements or suggestions you've > got would be very welcome (I can see some which we're planning on > addressing at some point, but fresh critical eyes are always welcome). > >>> However, off the top of my head, you should also look at Zope's component >>> model, Trac's component model, Twisted's model & PEAK, and any proposal >>> to say "this is the solution", needs to be compelling for all of these >>> projects. >> A standard component model could be used as a base for other more >> advanced needs. Most of those mentioned above seem to involve web >> application frameworks whereas my idea of a component model just assumes >> the paradigms of properties, methods, and events which may allow >> re-usable components at a base level in any environment. > > They do, however in particular, Trac's model whilst web oriented > strikes me personally as interesting and PEAK's is applicable, as I > understa
Re: Python component model
Richard Brodie wrote: > "Edward Diener No Spam" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> "Thinking in Java or C++" as opposed to Python does not mean anything to me >> as a general >> statement. I am well aware of the difference between statically and >> dynamically typed >> languages but why this should have anything to do with RAD programming is >> beyond me. Do >> you care to elucidate this distinction ? > > I think this blog entry http://osteele.com/archives/2004/11/ides > provides some insight into the point of view expressed. I think that one can easily be both, someone who is good at using a language and someone who is good at using a visual tool. The dichotomy presented in the article exists only for a small number of people. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Fredrik Lundh wrote: > "Edward Diener No Spam" wrote: > >> A RAD IDE tool to hook up components into an application or library ( >> module in Python ) has nothing to do with terseness and everything to do >> with ease of programming. > > python already has excellent and ridiculously easy-to-program ways to hook > things up. after all, hooking things up is what python programmers tend to > do, > most of their time. I agree. > > if you want better support for more precise hooking, post some examples. I want a design-time environment to hook up my objects in a visual way. I think it is easier than doing it manually, even in Python. > >> All you are saying is that you don't have a need for this, but perhaps >> others do. > > handwavy references to what "other may need" is another thing you should > avoid if you want your Python change proposal to be successful. I did not say what "others may need". -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Diez B. Roggisch wrote: >> While I understand dynamic typing, I still think it is possible to >> create attributes in a Python component model which could tell a RAD >> tool what type the attribute will encompass for the purpose of >> properties and events. Obviously a "name, type" tuple, among other >> possible information would have to be used. But given Python's amazingly >> flexible type and introspection system, this should be possible. > > The amazing flexibility stems from the fact that it is _runtime_. This is > _exactly_ the difference between static and dynamic typing. > > If a static analysis (_not_ importing the module, which can trigger > arbitrary code being run!!!) is supposed to deliver the component > architecture, you are either introducing static typing, or get into the > danger of lose coupling between declaration and implementation, rendering > the whole thing pretty useless. Yes, I am suggesting static typing functionality for a subset of Python attributes. How this can be done I am still investigating on my own. > > Of course, with a bit of discipline, you can create such a introspection > facility that offers its properties after a mere import, see ZOPE > interfaces for example. > > But in the end, it boils down to declaring stuff for that purpose alone, and > introducing static typing, whereas other languages declare typing for their > own needs, and add the component model upon that. > > And then you lose a _lot_ of what python makes powerful, for a very doubtful > benefit IMHO. Adding a feature, such as static typing functionality for the situation of doing visual RAD programming, does not "lose a _lot_ of what makes python powerful". My idea of adding static typing is not an attempt to change the language but rather to develop Python classes which encapsulate the idea of a variable and a type for the purposes of emulating component properties and component events. If a language addition is needed instead I will investigate how to propose it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Tim Chase wrote:
>> There's no doubt that Python's excellent introspection mechanism
>> allows an outside RAD-like tool to inspect the workings of any Python
>> object. But that does not make it a component model in my original use
>> of the term on this thread. A RAD tool needs to know what properties
>> and events within a class can be manipulated visually, and it needs to
>> be able to serialize those properties and events so that they are set
>> at run-time automatically once an object is created.
>
> A little visual inspection of some objects:
>
> [EMAIL PROTECTED]:~$ python
> Python 2.3.5 (#2, Sep 4 2005, 22:01:42)
> [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class Person(object):
> ... def __init__(self, name, age=None):
> ... self.name = name
> ... self.age = age
> ... def whoami(self):
> ... if self.age is not None:
> ...return "%s (%i)" % (
> ...self.name,
> ...self.age)
> ... return self.name
> ...
> >>> p = Person("Sandy")
> >>> [s for s in dir(p) if not s.startswith('_') and
> callable(eval('p.%s' % s))]
> ['whoami']
> >>> [s for s in dir(p) if not s.startswith('_') and not
> callable(eval('p.%s' % s))]
> ['age', 'name']
>
> Thus, you have the ability to find an object's methods/events (things
> that are callable()), and its properties (things that are not
> callable()). Any "RAD" tool that wants can pull these properties, just
> as my command-line RAD tool can ;)
Not all attributes are component properties in typical Visual RAD tool.
In most visual RAD tools which I have used a component property is a
publicly exposed type/name which may or may not have the backing of an
actual data member and does have a function to get the type's value if
the property is readable and does have a function associated with it to
set the type's value if the property is writable. This is very close to
the class properties in Python. The difference is that normally a type
must be associated with a property whereas in Python, as I understand
it, the type of a class property is unknown.
Furthermore by a component event I do not mean methods on the event
creator's side but rather an event source. This would look something
like a tuple of callable functions of a particular signature to which an
event sink could add an event handler so that when a particular event
occurred on the event source the event handlers added to the event
source would each be called.
>
> As for serializing them,
>
> >>> import shelve
> >>> d = shelve.open('tmp/stuff.shlv')
> >>> d['person'] = p
> >>> p = 'hello'
> >>> p
> 'hello'
> >>> p = d['person']
> >>> p.whoami()
> 'Sandy'
> >>> p.age = 42
> >>> p.whoami()
> 'Sandy (42)'
> >>> d['person'] = p
> >>> d.close()
> >>> p = 'hello2'
> >>> p
> 'hello2'
> >>> d = shelve.open('tmp/stuff.shlv')
> >>> p = d['person']
> >>> p.whoami()
> 'Sandy (42)'
>
> which seems to work fine for me. This can be used for creating all
> sorts of flavors of objects at design time, storing them, and then
> restoring them at runtime.
I realize that Python has excellent abilities in all these areas,
including serialization. But a component model for serialization must
not only have the ability of serializing and deserializing all of the
component's data, as well as any base classes, it must also have a means
of allowing the class itself to specify which data needs to be
serialized and which not, as well as allow for the class to seriliaze
all or part of its own data.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Fredrik Lundh wrote: > Edward Diener No Spam wrote: > >> There's no doubt that Python's excellent introspection mechanism allows >> an outside RAD-like tool to inspect the workings of any Python object. >> But that does not make it a component model in my original use of the >> term on this thread. A RAD tool needs to know what properties and events >> within a class can be manipulated visually, and it needs to be able to >> serialize those properties and events so that they are set at run-time >> automatically once an object is created. > > external serialization was not part of your original definition. Well, knock me over. > > I think you have to be a *lot* more concrete here. repeatedly referring to > "some kind of hypothetical property (that isn't a property)" and "some kind > of hypothetical event (that isn't a public method)" and "some kind of hypo- > thetical RAD tool" won't get you anywhere. My OP was just to query whether a component model existed for Python, like JavaBeans for Java or .Net for C#, C++/CLI etc. After that came suggestions of what I thought such a component model was about, which I thought I answered generally. Not you want details. No doubt next will come a demand for code. OK, here is my idea of what such a component model envisages as a list of items. After this, unless I get some intelligent comments from people who might be interested in what I envision, or something very similar, I will be off to investigate it myself rather than do battle with the horde of people who will just tell me that Python, being a great language, does not need what I have suggested. 1) Component property: This is a glorified attribute with a type that can either be specified in a "static" manner, or always be discovered dynamically, or have converters back and forth between a string and the actual value represented by the component property. A component property has a getter function to retrieve the value if it is readable and a setter function to set the value if it is writable. It must be either readable or writable or both. A component property is not any Python class attribute since a component has the right to specify only certain values as manipulatable in a design-time RAD environment. 2) Component event: This is an type which encapsulates an array, or a list of callable objects with the same function signature, along with the functionality to add and remove elements from the array, as well as cycle through the array calling the callable objects as a particular event is triggered. A component event is an event source for a particular event. Component events have to be dicoverable by the Visual RAD system so that an object's appropriate event handler, an event sink, can be hooked to the component event itself, an event source, through a design time interface which propagates the connection at run-time. 3: Component serialization: A component which has its properties and events set by a visual design-time RAD environment needs to be serialized at design time and deserialized at run-time. This can be a default serialization of all component properties and events, or the component itself can participate in the serilization effort either wholly or partly. 4) Custom property and component editors: A component editor can present a property editor or an editor for an entire component which the visual design-time RAD environment can use to allow the programmer end-user of the component to set or get component property values. Normally a design time environment will present default property editors for each component property type, but a component can override this. 5) Custom type converters: A component should be able to specify a custom converter for any property to convert, in both directions or either direction, between the property's string value as seen by a property editor and the actual value of the component property's type. This is the general gist of those things which are needed in a visual Design-time RAD environment. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Paul Boddie wrote: > [EMAIL PROTECTED] wrote: >> Edward> My OP was just to query whether a component model existed for >> Edward> Python, like JavaBeans for Java or .Net for C#, C++/CLI >> Edward> etc. >> >> For those of us who've never used Java, .Net or C++/CLI, a more concrete >> description of what you were after from the beginning would have been >> helpful. > >>From vague recollections of the original Java Beans technology, the > primary "innovation" was to have getProperty and setProperty methods, > along with things like isCapability and hasProperty, if I remember > correctly. None of this was really shocking to anyone using Python, > mostly because Python had __getattr__ and __setattr__ even back then > for customising real property/attribute access, and Python's run-time > introspection capabilities were superior to Java's (and probably still > are). There is no argument on my part that Python's introspection and metadata capabilities are superior to Java, as well as its potential attribute as component property model. In the theoretical Python model I proposed, the designer of the component must have the ability to specify which of the component's attributes are properties and how this is controlled ( via __getattr__ and __setattr__ ? descriptors as someone else suggested ? other ideas ? ). Merely saying that all of an object's attributes are component properties for the purposes of a visual RAD designer can not be correct. I actually think that Java's notion of preoperties in JavaBeans, which are just getter and setter functions with a particular naming convention, determined by Java as a default, or through an associated BeanInfo class, is rather klutzy and much prefer that of .Net or Borland's VCL where a particular language construct is used for properties instead. Of course with Python's superior metadata abilities, a particular new language construct shouldn't be necessary. > > The other innovation was the introduction of standard interfaces for > listening to and dispatching events, where you implement some listener > interface and respond to events in order to "care about" those events. > I don't recall any particularly good mechanisms for connecting beans to > each other in order to fire off events, although the beanbox (or > whatever the graphical tool originally promoted was called) and/or the > IDE is supposed to help you with that part of the work. The beanbox did nothing to help setup events, event sources, or event listeners. It just presented a graphical example of a visual RAD tool which could tie event sources to event listeners. It is onerous in JavaBeans to connect event sources to event listeners, and takes a good deal of manual coding although doing it is easy to understand. > > The groovy 1990s API 1997. Again Borland's VCL or .Net have much better solutions for events but again require language constructs which Python ought not need given its strong metadata possibilities to supply a component event model. > is actually viewable in various places; here, for > example: > > http://www.doc.ic.ac.uk/~jpc1/linux/bdk-doc-1.0/apis.html The BDK is no longer supported in the latest version of Java and JavaBeans. Instead there is a Bean Builder at https://bean-builder.dev.java.net/ . > > Despite the supposedly exciting advances heralded by Java Beans, a > large part of the technology was just codifying existing practices and > techniques, but it could be argued that such techniques have been > superseded by signal/slot mechanisms and more advanced event > architectures (pioneered by frameworks like Qt and since adopted by > Gtk, I believe). I agree and I would want to have a component event model for Python that is much superior to the JavaBeans event model in ease of use. A much better ideal for component properties and component events is presented by .Net, where there are actual language keywords which perform the magic. I would guess that Qt and Gtk also follow a better ease of use path, perhaps with macros in C++. But Python should be able to do as good or better than any of these environments. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
fumanchu wrote:
> Edward Diener No Spam wrote:
>> OK, here is my idea of what such a component model envisages as a list
>> of items. After this, unless I get some intelligent comments from people
>> who might be interested in what I envision, or something very similar, I
>> will be off to investigate it myself rather than do battle with the
>> horde of people who will just tell me that Python, being a great
>> language, does not need what I have suggested.
>
> [This quote hacked up by me:]
>> 1) Component property: This is a glorified attribute with a type that
>> a) can be specified in a "static" manner, or discovered dynamically,
>> b) has converters between a string and the actual value
>> c) has a getter function to retrieve the value if it is readable and a
>> setter function to set the value if it is writable.
>> d) be either readable or writable or both.
>> e) not any Python class attribute since a component has the right
>> to specify only certain values as manipulatable in a design-time
>> RAD environment.
>
> Whenever you say "glorified attribute", your first thought should be
> "Python descriptor" (but not your last--it's not a cure-all). They are
> able to do all of (a, b, c, d, e) which I marked in your text above.
> For example, here's a descriptor for
> attributes-you-want-to-persist-in-a-database from my ORM, Dejavu (see
> http://projects.amor.org/dejavu/browser/trunk/units.py#l290):
>
>
> class UnitProperty(object):
> """Data descriptor for Unit data which will persist in storage."""
>
> def __init__(self, type=unicode, index=False, hints=None, key=None,
> default=None):
> self.type = type
> self.index = index
> if hints is None: hints = {}
> self.hints = hints
> self.key = key
> self.default = default
>
> def __get__(self, unit, unitclass=None):
> if unit is None:
> # When calling on the class instead of an instance...
> return self
> else:
> return unit._properties[self.key]
>
> def __set__(self, unit, value):
> if self.coerce:
> value = self.coerce(unit, value)
> oldvalue = unit._properties[self.key]
> if oldvalue != value:
> unit._properties[self.key] = value
>
> def coerce(self, unit, value):
> if value is not None and not isinstance(value, self.type):
> # Try to cast the value to self.type.
> try:
> value = self.type(value)
> except Exception, x:
> x.args += (value, type(value))
> raise
> return value
>
> def __delete__(self, unit):
> raise AttributeError("Unit Properties may not be deleted.")
>
>> a) can be specified in a "static" manner, or discovered dynamically,
>
> The "component model" can either scan a class for instances of
> UnitProperty or keep a registry of them in the class or elsewhere (via
> a metaclass + add_property functions).
>
>> b) has converters between a string and the actual value
>
> Note the "coerce" function above. Something similar could be done for
> serialization (which I can prove in my case because I use UnitProperty
> to help produce SQL ;) but you could just as easily pickle
> unit._properties and be done with it.
>
>> c) has a getter function to retrieve the value if it is readable and a
>> setter function to set the value if it is writable.
>> d) be either readable or writable or both.
>
> Descriptors that only have __get__ are read-only; if they have __set__
> they are read-write.
>
>> e) not any Python class attribute since a component has the right
>> to specify only certain values as manipulatable in a design-time
>> RAD environment.
>
> Right. Descriptors allow the creator of a class to use "normal"
> attributes (including functions) which don't participate in the
> component model.
>
>> 2) Component event: This is an type which encapsulates an array, or a
>> list of callable objects with the same function signature, along with
>> the functionality to add and remove elements from the array, as well as
>> cycle through the array calling the callable objects as a particular
>> event is triggered. A component event is an event source for a
>> particular event. Component events have to be dicoverable by the Visual
>> RAD system so that an object's appropriate event handler, an event sink,
>> can be hooked to the component event its
Re: Python component model
Kay Schluehr wrote: > fumanchu wrote: > >>> 4) Custom property and component editors: A component editor can present >>> a property editor or an editor for an entire component which the visual >>> design-time RAD environment can use to allow the programmer end-user of >>> the component to set or get component property values. Normally a design >>> time environment will present default property editors for each >>> component property type, but a component can override this. >> This is the hard part. I believe Dabo has done some work in this space, >> but this is where the tight coupling comes in between code and tool, a >> coupling which Python has traditionally resisted. > > I do think it's just about presenting component properties and their > types / value ranges. I do think this can be easily achieved using > decorators that might also add the right kind of token for > introspection purposes to the function/method attributes. Descriptors > i.e. customized binding semantics might cover one aspect of > componentization but as I understood Edward he asked for uniform > declarative semantics. Uniform in the sense that a visual RAD tool introspecting a Python class would be able to say that s type X is a component property and type Y is a component event, and everything is is just normal Python code which the RAD tool can ignore. > Components in this sense are just specialized > objects such as TestCase classes in the PyUnit framework. Totally agreed. But the common functionality they add is valuable to visual RAD tools. > What I still > do not understand is the reference to "many RAD" tools which is > completely hypothetical to me. You are right that I should not have mentioned this without experience with the many Python tools, notable Python web page development environments, which are out there. > The portability of components across > different GUI designers for the same underlying toolkit is a quite > speculative future requirement to say the least. It's been a success in the Java world with JavaBeans and EJBs within environments like Eclipse, NetBeans, JBuilder, and others; and its been a success in the .Net world with .Net components within Visual Studio, Borland Development Studio, and potentially others, so ideally it could be a success in the Python world. I believe the only knock against Python, as opposed to Java or .Net, is that it does not present enough ease of use environments to creating large scale applications, whether Linux, Windows, or Web applications. I believe part of that reason is because Python developers who, whether they wanted to distribute their classes for free or want to sell them for a profit, are presented with endless technologies built with Python, each one demanding a slightly different approach to class reusability, are reticent to develop their ideas for many different environments. Wanting a common PME component model is a way of saying that Python class developers can develop their classes as components and at least at the base level can expect them to work flawlessly in any Python environment. I am NOT against a particular environment building further requirements on top of a common Python component model, and in fact would expect it in many cases. But given inheritance in OOP, and in Python of course, this might be as easy for me as deriving a new class from my particular base class component for a particular visual RAD development environment, adding the extra function needed onto my derived class, and away we go. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Fredrik Lundh wrote: > fumanchu wrote: > >>> 4) Custom property and component editors: A component editor can present >>> a property editor or an editor for an entire component which the visual >>> design-time RAD environment can use to allow the programmer end-user of >>> the component to set or get component property values. Normally a design >>> time environment will present default property editors for each >>> component property type, but a component can override this. >> >> This is the hard part. I believe Dabo has done some work in this space, >> but this is where the tight coupling comes in between code and tool, a >> coupling which Python has traditionally resisted. > > that's not that hard on a pure technical level; even a "basic" tool > like IDLE can hook itself into an executing Python process. once you're > hooked up, you can inspect and modify most about everything. > > for example, doing remote tweaking of live Tkinter widget trees is > pretty straight-forward. > > coming up with a good way to capture the modifications, and use them in > your actual application, is a bit harder. do you really want to replace > plain old source code with some kind of more or less obscure resource > files? The Visual Studio RAD IDE environment actually modifies source code constructors, via an InitializeComponent() function called from it, in order to set properties and events in components. It does mark the function as such with comments in the source code. OTOH Borland's VCL uses the resource file technique you scorn above, linking in the code via resources and automatically updating a component's properties and events from base class components constructors. I believe Java's JVM automatically deserializes .ser files at run-time saved by a RAD designer in order to set properties and events on an object of a class. There are obviously numerous techniques, so one should theoretically work well with Python. > > and designing a metadata vocabulary that's powerful enough to be useful > for more than just one or a few target domains might be really hard. That's the are I am most interested in. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Peter Wang wrote: > Edward Diener wrote: >> It looks as if traits is an attempt to create a "property" in the >> component terminology which I originally specified. I will take a look >> at it. > > Traits is frighteningly similar to the requirements that you laid out > in your post (the example for Skip), including delegates! I would like > to point out, however, that traits is a *general* component framework > for python that facilitates implementing the observer pattern and a > higher level of introspection. It can be used to build applications > that have no visual interfaces at all, but wish to benefit from the > "reactive programming" style that componentized, event-based > programming encourages. (induces?) Thanks for the explanation. I was too quick in seeing Traits as only a version of properties without realizing that it included much more. > > Traits UI, which Robert only alluded to, is actually very much the sort > of RAD environment you have described. It builds upon the component > model, and uses introspection to automagically create nice widgets for > your model, but adds mechanisms for specifying controllers, customizing > behavior, and generically composing complicated forms from simpler > ones. There is even a visual "builder" tool for it called VET that > closely resembles Delphi/C++ Builder. (The VET itself is, of course, > written using Traits UI.) I have downloaded both Traits and Traits UI and will look at both. > > Envisage, the plugin application framework, can use the traits > component models and the TraitsUI interfaces to roll out very dynamic > applications, whose underlying models are all live components that can > be scripted, twiddled with from an embedded Python shell, etc. > >> Already subscribed. Thanks ! > > Please contribute ideas or ask conceptual questions! It would be easier for me if you could get an NG somewhere for Enthought, perhaps on GMane, since I always find mailing lists much more clunky than a good NG. But that is up to Enthought. > > Oh, and disclaimer: I also work at enthought. :) That's fine. It is the ideas about a PME component model for Python in which I was interested, no matter where it originates. Thanks for the encouraging reply. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python component model
Kay Schluehr wrote: > val bykoski wrote: >> Peter Wang wrote: >>> Edward, >>> >>> This isn't in response to any specific one of the 100+ posts on this >>> thread, but I justed wanted to encourage you to continue your >>> investigation into Python component models and maybe looking for some >>> common ground between them. Frequently the individual developers are >>> too heads-down on working on their own things to do a broad survey, so >>> I think this would be very useful indeed. >>> >>> I wouldn't have felt it necessary to post this except for the large >>> number of posts along the lines of "foo.dict is introspective enough >>> for me!". I think you might have an easier time evangelizing the >>> principle of component-oriented programming (or "event-based", or >>> "reactive", or whatever) if you separated it from the notions of RAD UI >>> development. There is a very large difference between writing >>> components and writing objects, and it seems that most people arguing >>> "python doesn't need components" don't see this distinction. >>> >>> For me, it's the difference between writing "live" objects and "dead" >>> objects. Live objects not only encapsulate implementations of an >>> interface with some state, but they also encapsulate handling of >>> events, i.e. responses to changes in their environment. Dead objects >>> have methods but there has to be a function somewhere that knows which >>> dead object to call with what parameters at exactly the right time. >>> (The only mechanism for managing this complexity is to create ever more >>> functions at ever higher levels of abstraction, or to have a >>> proliferation of nebulously-defined "manager" objects.) IMHO once you >>> cross this chasm and are able to model your problem domain with live >>> objects that go off and automatically respond to the runtime >>> environment and Do the Right Thing, it's very hard to go back to a dead >>> object mindset. I can understand, however, that until one makes this >>> leap, it might seem like an academic and useless distinction. >>> >>> -peter >>> >> Excellent post, Peter. Thanks for great clarification. Looking from a >> physicist' perspective, im always trying to compare/evaluate languages >> from "the physical reality/dynamics" angle. So, the run-time >> space/dynamics is the only one that matches the natural "always-runtime" >> objects - atoms, molecules, EM fields, biological cells(?). It is the >> *reactive* world with event/forces-driven dynamics. Seemingly, there is >> nothing beyond that, including biology. > > A more conventional notion is that of static/dynamic properties of a > language. Component models that guarantee certain properties at compile > time are easily checked for consistency but to many programmers ( I > guess most of the programmers who attend to this list ) they are > inflexible: you might change or adapt your components according to > events, switch between entities, enable dynamic configuration etc. This > can be achieved in C++, Java etc. as well but not without pain. Having "static" properties and events is necessary for visual RAD programming environments, where connections are being setup between events and event handlers, and properties are being initialized, at design time. This does not preclude the normal "dynamic" attributes of Python. However if Python programmers reject such visual RAD programming environments as having any value, then they probably won't be interested in a common component model for them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lead Software Engineer
Emma wrote: > Successful candidates meet the following requirements: > · A burning desire to build rock-solid apps that people will be > unable > to live without I use to have a burning desire to cleverly answer questionnaires for companies which either don't exist or, if they do, don't tell you who they are, where they are located, or what they are offering, but I gave it up in infancy. -- http://mail.python.org/mailman/listinfo/python-list
TypeError: unbound method must be called with class instance 1st argument
I'm a novice at Python, and found some code samples on how to use
threads. My script is being run by a product that contains a Jython
interpreter. Can someone please explain why I get the following error:
Traceback (innermost last):
File "/full/path/to/file/GenerateData.py", line 104, in ?
File "/full/path/to/file/GenerateData.py", line 34, in __init__
TypeError: unbound method must be called with class instance 1st
argument
Here are the important pieces of my GenerateData.py script. Note that
"scriptinterface" is something provided by the product to allow my
script to interface with it. Line 104 is the last line -- the one that
creates a GenThread and calls start() on it.
import sys
# need this section otherwise the import random won't work
if sys.path.count('/usr/local/lib/python2.2/') == 0:
sys.path.append('/usr/local/lib/python2.2/')
import random
import time
import threading
from java.lang import String
from jarray import array
class GenThread(threading.Thread):
def __init__(self, ipAddress, port):
threading.Thread.__init__()
self.ipAddress = ipAddress
self.port = str(port)
def run(self):
#
# code
#
GenThread(scriptinterface.getSnmpIPAddress(),
scriptinterface.getSnmpPort()).start()
--
http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: unbound method must be called with class instance 1st argument
Matimus wrote: > > Can someone please explain why I get the following error: > > The following line: > threading.Thread.__init__() > Should be written as: > threading.Thread.__init__(self) Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4 | 7.3 The for statement
brainsucker wrote: > Python 2.4 | 7.3 The for statement: > --- > > for_stmt ::= "for" target_list "in" expression_list ":" > suite ["else" ":" suite] > > > New for statement: > -- > > for_stmt ::= "for" target_list "in" expression_list > [ "and" expression ] ":" > suite ["else" ":" suite] > > ** If the expression evaluates to False before > entering the for, jump else. > ** If the expression is evaluated to False after > the first iteration, break. I think that your idea is good but as others said the "and" literal could be confusing. ¿Maybe we can use another word instead of "and"? The for definition could be like this: for_stmt ::= "for" target_list "in" expression_list [ "until" expression ] ":" suite ["else" ":" suite] or some other word that clarifies the work of the expression leave_cond_1 = False leave_cond_2 = False mylist = [1,2,3,4,5] for item in mylist until leave_cond_1 or leave_cond_2: print item -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting HTTP responses - a python linkchecking script.
[EMAIL PROTECTED] a écrit : > Hi Folks, > > I'm thinking about writing a script that can be run over a whole site > and produce a report about broken links etc... > > I've been playing with the urllib2 and httplib modules as a starting > point and have found that with urllib2 it doesn't seem possible to get > HTTP status codes. > > I've had more success with httplib... > Firstly I create a new HTTPConnection object with a given hostname and > port then I try connecting to the host and catch any socket errors > which I can assume mean the server is either down or doesn't exist at > this place anymore. > If the connection was successful I try requesting the resource in > question, I then get the response and check the status code. > > So, I've got the tools I need to do the job sufficiently. Just > wondering whether anybody can recommend any alternatives. > > Cheers, >-Blair > have a look at urllib2 - The Missing Manual http://www.voidspace.org.uk/python/articles/urllib2.shtml -- http://mail.python.org/mailman/listinfo/python-list
