Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke

Improved link - 
http://docs.python.org/3.0/reference/datamodel.html#object.__iadd__
--
http://mail.python.org/mailman/listinfo/python-list


braces fixed '#{' and '#}'

2009-01-18 Thread v4vijayakumar
I saw some code where someone is really managed to import braces from
__future__. ;)

def test():
#{
print "hello"
#}
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt, Cannot send events to objects owned by a different thread?

2009-01-18 Thread icejobjob

AE•X‰ÍŠúA‚»‚ê‚à’´AE•X‰ÍŠú‚ÉŽ„‚½‚¿‚Í’¼–Ê‚µ‚Ä‚¢‚Ü‚·

‚±‚́A'AEŠˆ“®'
(http://www.pwblog.com/user/xru01/syusyoku/)‚Í•À‘å’ï‚Ì“w—͂ł͏æ‚èØ‚邱‚Æ‚ª¢“ï‚ÆŒ¾‚í‚ê‚Ä‚¢‚Ü‚·B

•Ä‘AƒAƒƒŠƒJ‚̃Tƒuƒvƒ‰ƒCƒ€‚ð”çØ‚è‚Ɉø‚«‹N‚±‚³‚ꂽ¡‰ñ‚Ì•s‹µA‚»‚ꂱ‚»””NŠÔ‚ɂ킽‚Á‚āA¢ŠEŒoÏ‚ɃCƒ“ƒpƒNƒg‚ð—^‚¦‘±‚¯‚é‚Å‚µ‚傤B

‚±‚ÌŽžŠú‚́A¡‚Ì‚*‚È‚½‚ª’¼–Ê‚µ‚Ä‚¢‚éAEŠˆ“®‚Æ‚¢‚¤ƒCƒxƒ“ƒg‚́A‚*‚È‚½‚̐l¶AAEl¶‚Ì‘å‚«‚ȃEƒGƒCƒg‚ðè‚߂邱‚Æ‚Æ‚È‚è‚Ü‚·B

AEŠˆ“®‚́A‹Zp‚Æ’mŽ¯‚ŏæ‚èØ‚邱‚Æ‚ªo—ˆ‚Ü‚·BAE•X‰ÍŠúAâ‘΂Ɍã‰÷‚µ‚È‚¢‚悤‚É‘S—͂Ő킢‚Ü‚µ‚傤B


-- 
icejobjob

icejobjob's Profile: http://forums.yourdomain.com.au/member.php?userid=5313
View this thread: http://forums.yourdomain.com.au/showthread.php?t=18594

--
http://mail.python.org/mailman/listinfo/python-list


bin = FieldStorage(fp=environ['wsgi.input'], environ=environ)

2009-01-18 Thread gert
in python3.0 this does not work

File "/usr/python/lib/python3.0/email/feedparser.py", line 99, in push
data, self._partial = self._partial + data,
TypeError: Can't convert 'bytes' object to str implicitly

So what do i need to wrap around environ['wsgi.input'] so it does
work ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: English-like Python

2009-01-18 Thread The Music Guy
Wow, impressive responses.

It sounds like the general consensus is that English would not be a good
choice for programming even if there were an interpreter capable of
turning human language into machine language. But that makes sense; even
English professionals have trouble understanding each other sometimes.
Until that problem is somehow overcome, there's not much hope of
computers to overcome it.


--
http://mail.python.org/mailman/listinfo/python-list


output problem

2009-01-18 Thread Jean-Paul VALENTIN
Feature? the output of below Hello program he0.py started from command
line looks as follows:
F:\prompt>he0.py
Hello
F:\prompt>

'Hello' was sent with sys.stdout.write, so "without newline".
But why cannot be output (more logically):
F:\prompt>he0.py
HelloF:\prompt>

Is it normal? Is there any means or workaround to obtain that output if
I wish??

__
#!/usr/bin/python
#-*- coding: iso-8859-15 -*-
import sys
sys.stdout.write('Hello')

 
About Ingenico: Ingenico is the world's leading provider of payment solutions, 
with over 15 million terminals deployed across the globe. Delivering the very 
latest secure electronic payment technologies, transaction management and the 
widest range of value added services, Ingenico is shaping the future direction 
of the payment solutions market. Leveraging on its global presence and local 
expertise, Ingenico is reinforcing its leadership by taking banks and 
businesses beyond payment through offering comprehensive solutions, a true 
source of differentiation and new revenues streams.
 This message may contain confidential and/or privileged information. If you 
are not the addressee or authorized to receive this for the addressee, you must 
not use, copy, disclose or take any action based on this message or any 
information herein. If you have received this message in error, please advise 
the sender immediately by reply e-mail and delete this message. Thank you for 
your cooperation.
 P Please consider the environment before printing this e-mail
 
 
--
http://mail.python.org/mailman/listinfo/python-list


s=ascii(hexlify(urandom(10)))

2009-01-18 Thread gert
I expected that py3 did not converted the b'...' indication too ?

b'afc76815e3fc429fa9d7'

--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-18 Thread Matimus
The goals are listed here: 
http://codespeak.net/pypy/dist/pypy/doc/architecture.html

Speed is mentioned, but as a secondary concern. The main goal seems to
be to create a vehicle into exploring the concept of dynamic languages
themselves. If that seems amorphous then it is because it is a
research project.

Matt
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-18 Thread Russ P.
Wow! That was an instant classic! I just have a couple of points to
add.

The suggestion was made (not by you) that data hiding is worthless
because it can be defeated anyway. According to that kind of
reasoning, locks are worthless because they can be picked, cut, or
just blown off. I know that the lock on my front door cannot stop
someone who is determined to get into my house, but I think I'll keep
it anyway. I'm just irrational that way, I guess.

As I said before, I don't know if enforced data hiding can be added to
Python without ruining the language (or if it can be added at all, for
that matter). But if it can, I think the cleanest and most elegant
syntax would be to add the keyword "private" or "priv" and use it
essentially the same way it is used in Java, C++, and now Scala. That
would eliminate the need for leading underscores, which I personally
find tacky.

Since new attributes can be added outside of the constructor, the
private declaration would also have to be allowed outside the
constructor and for existing attributes.

One more thing. If an airplane is going to flip upside down and fly
straight into the ground, the passengers may as well be nuns. They are
better prepared for the result.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread Aaron Brady
On Jan 18, 6:56 am, andrew cooke  wrote:
> On Jan 18, 9:40 am, Marc 'BlackJack' Rintsch  wrote:
>
> > On Sun, 18 Jan 2009 04:24:04 -0800, andrew cooke wrote:
> > > my argument was that *= is not treated as = and *, but as a completely
> > > new operator (the docs even say that the implementation need not return
> > > self which suggests some pretty extreme semantics were envisaged).
>
> > What do you mean by "suggests … extreme semantics"?  Most natural thing
> > is to use numbers and there you *have* to be able to return something
> > different than `self` to get anything useful.  For instance:
>
> >  n *= 3
>
> > with `n` bound to a number different from zero can't return `self` from
> > `__imul__`.
>
> in your example, n is not a number, it is a mutable variable, and its
> value changes.
>
> when n is an instance implementing __imul__ the natural analogue is
> that the internal state of the instance changes.
>
> either i have misundertstood you, or you have misunderstood __imul__,
> or you are treating = as equality, or maybe you are thinking of a pure
> language that creates new instances?  python is impure.
>
> anyway, my original request is moot.  i was assuming that this was a
> "capricious" restriction.  in fact it's related to what i thought were
> operators actually being assignments, and so no change is possible
> (until python 4.0 when guido will finally see the light and move to s-
> expressions, at which point everyone will stop using the language ;o)
>
> andrew

Not sure if this ties in, but:

>>> ['a'].__imul__(2)
['a', 'a']
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
http://bugs.python.org/issue4986

Sorry for the noise,
Andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there something like a module decorator ?

2009-01-18 Thread Stef Mientki

Diez B. Roggisch wrote:

Stef Mientki schrieb:

hello,

I wonder if there's something like a module decorator.
I could use it in debugging a large highly dynamical program.


No, there isn't. This has been discussed a while ago:

http://groups.google.de/group/comp.lang.python/browse_thread/thread/215216a1e13ba2c6 



Diez
--
http://mail.python.org/mailman/listinfo/python-list

thanks for the information.
cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there something like a module decorator ?

2009-01-18 Thread Diez B. Roggisch

Stef Mientki schrieb:

hello,

I wonder if there's something like a module decorator.
I could use it in debugging a large highly dynamical program.


No, there isn't. This has been discussed a while ago:

http://groups.google.de/group/comp.lang.python/browse_thread/thread/215216a1e13ba2c6

Diez
--
http://mail.python.org/mailman/listinfo/python-list


is there something like a module decorator ?

2009-01-18 Thread Stef Mientki

hello,

I wonder if there's something like a module decorator.
I could use it in debugging a large highly dynamical program.

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
On Jan 18, 9:56 am, andrew cooke  wrote:

> either i have misundertstood you

ah, i see your point.  sorry, andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
On Jan 18, 9:40 am, Marc 'BlackJack' Rintsch  wrote:
> On Sun, 18 Jan 2009 04:24:04 -0800, andrew cooke wrote:
> > my argument was that *= is not treated as = and *, but as a completely
> > new operator (the docs even say that the implementation need not return
> > self which suggests some pretty extreme semantics were envisaged).
>
> What do you mean by "suggests … extreme semantics"?  Most natural thing
> is to use numbers and there you *have* to be able to return something
> different than `self` to get anything useful.  For instance:
>
>  n *= 3
>
> with `n` bound to a number different from zero can't return `self` from
> `__imul__`.

in your example, n is not a number, it is a mutable variable, and its
value changes.

when n is an instance implementing __imul__ the natural analogue is
that the internal state of the instance changes.

either i have misundertstood you, or you have misunderstood __imul__,
or you are treating = as equality, or maybe you are thinking of a pure
language that creates new instances?  python is impure.

anyway, my original request is moot.  i was assuming that this was a
"capricious" restriction.  in fact it's related to what i thought were
operators actually being assignments, and so no change is possible
(until python 4.0 when guido will finally see the light and move to s-
expressions, at which point everyone will stop using the language ;o)

andrew
--
http://mail.python.org/mailman/listinfo/python-list


is there something like a module decorator ?

2009-01-18 Thread Stef Mientki

hello,

I wonder if there's something like a module decorator.
I could use it in debugging a large highly dynamical program.

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread Marc 'BlackJack' Rintsch
On Sun, 18 Jan 2009 04:24:04 -0800, andrew cooke wrote:

> my argument was that *= is not treated as = and *, but as a completely
> new operator (the docs even say that the implementation need not return
> self which suggests some pretty extreme semantics were envisaged).

What do you mean by "suggests … extreme semantics"?  Most natural thing 
is to use numbers and there you *have* to be able to return something 
different than `self` to get anything useful.  For instance:

 n *= 3

with `n` bound to a number different from zero can't return `self` from 
`__imul__`.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
On Jan 18, 9:01 am, Chris Rebert  wrote:
> Indeed. Python happens to in this case draw the line at using the
> augmented assignment operators for non-assignment. I personally see
> this as reasonable because the = symbol has a consistent meaning in
> Python (assignment) whereas the other plain operators, as you bring
> up, consistently have no predetermined meaning;

my argument was that *= is not treated as = and *, but as a completely
new operator (the docs even say that the implementation need not
return self which suggests some pretty extreme semantics were
envisaged).  however, as i've just commented elsewhere, this
commitment to operators was only half-baked because they are parsed as
assignments.

anyway, to reply to your comment - *= is not predetermined.  it is
determined by __imul__ which is user-definable.

> but I do agree that it
> is in a sense an arbitrary restriction, like many programming language
> design choices. However, Python was not explicitly designed for
> creating DSLs,

python is a general programming language.  as far as i can make any
sense at all of your argument it seems to be "you are asking for
change, but this is not how the current system works".  to which the
obvious answer is: if it did work that way i wouldn't be asking for
change.

andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke

Not sure if you were saying this, but the underlying technical reason
for this issue is that they are treated as assignment rather than
operators in the language spec -
http://docs.python.org/3.0/reference/simple_stmts.html#augmented-assignment-statements

I think this explains why they are not listed in the operator
precedence table http://docs.python.org/3.0/reference/expressions.html#summary

I think that's unfortunate in a language with mutable objects, but it
makes the decision seem much less arbitrary...

Cheers,
Andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread Chris Rebert
On Sun, Jan 18, 2009 at 3:42 AM, andrew cooke  wrote:
>> Therefore, Python requires you to rewrite the code in some other way
>> that makes your intentions more clear. For instance, why not use the
>> << operator instead?
>
> Right, but you're guessing what the context is.  Within a DSL it often
> makes a lot of sense to use operators for reasons that weren't
> originally intended.
>
> You even make the same case yourself indirectly.  The same argument
> you make could be made to say that << should only operator on values
> that can be shifted.  Now thankfully there is no way to test for that,
> so there is no restriction and, consequently, it is now widely
> accepted that no-one (even people arguing the case for constraints!)
> think it odd to use << for something other than its initial use.
>
> Obviously this kind of discussion has gone on since languages were
> first invented - it's the "how much rope" argument.  So rather than
> continue down that road I would just like to say that this feels like
> an inconsistency.  The other operators are *not* as restricted and
> this is making my life harder.

Indeed. Python happens to in this case draw the line at using the
augmented assignment operators for non-assignment. I personally see
this as reasonable because the = symbol has a consistent meaning in
Python (assignment) whereas the other plain operators, as you bring
up, consistently have no predetermined meaning; but I do agree that it
is in a sense an arbitrary restriction, like many programming language
design choices. However, Python was not explicitly designed for
creating DSLs, so it's kinda odd to complain about something Python
never claimed to support in the first place (although I do favor the
DSL in general-purpose-PL paradigm).

> It may sound crazy, but this may force me to use * and ** instead (the
> context is a language feature related to *args and **kargs, so the *
> and ** help convey the meaning).  And they have a much much stronger
> meaning to users, which will make my DSL harder to understand.  So in
> this case a blunt knife is making life harder.

Perhaps if you explained your particular predicament in more depth,
someone might be able to offer a workable suggestion.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Am I interacting with the database correctly?

2009-01-18 Thread Hussein B
Hey,
I'm new with database interactions in Python and I'm not sure if I'm
handling the cursor and transactions correctly:

cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(flate_rate_pkgs_sql)
rows = cursor.fetchall()
#I have for loop here to iterate over rows
   cursor.execute()
   rows = cursor.fetchall()
   # some more cursor.execute() calls but only SQL select statements
   # here is another for loop that contains try block
  # here are cursor.execute() calls, both insert and update
  db.commit()
  # in the except code block, I use db.rollback()

As you see, my script contains only one db object and one cursor
object and both the db and cursor objects are used multiple times, it
is ok?
As you might figured, this is a script for reports :)
Thanks.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Totally confused by the str/bytes/unicode differences introduced in Pythyon 3.x

2009-01-18 Thread John Machin
On Jan 18, 2:02 pm, Terry Reedy  wrote:
> John Machin wrote:
> > On Jan 18, 9:10 am, Terry Reedy  wrote:
> >> Martin v. Löwis wrote:
> > Does he intend to maintain two separate codebases, one 2.x and the
> > other 3.x?
>  I think I have no other choice.
>  Why? Is theoretically possible to maintain an unique code base for
>  both 2.x and 3.x?
> >>> That is certainly possible! One might have to make tradeoffs wrt.
> >>> readability sometimes, but I found that this approach works quite
> >>> well for Django. I think Mark Hammond is also working on maintaining
> >>> a single code base for both 2.x and 3.x, for PythonWin.
> >> Where 'single codebase' means that the code runs as is in 2.x and as
> >> autoconverted by 2to3 (or possibly a custom comverter) in 3.x.
>
> >> One barrier to doing this is when the 2.x code has a mix of string
> >> literals with some being character strings that should not have 'b'
> >> prepended and some being true byte strings that should have 'b'
> >> prepended.  (Many programs do not have such a mix.)
>
> >> One approach to dealing with string constants I have not yet seen
> >> discussed here is to put them all in separate file(s) to be imported.
> >> Group the text and bytes separately.  Them marking the bytes with a 'b',
> >> either by hand or program would be easy.
>
> > (1) How would this work for somebody who wanted/needed to support 2.5
> > and earlier?
>
> See reposts in python wiki, one by Martin.

Most relevant of these is Martin's article on porting Django, using a
single codebase. The """goal is to support all versions that Django
supports, plus 3.0""" -- indicating that it supports at least 2.5,
which won't eat b"blah" syntax. He is using 2to3, and handles bytes
constants by """django.utils.py3.b, which is a function that converts
its argument to an ASCII-encoded byte string. In 2.x, it is another
alias for str; in 3.x, it leaves byte strings alone, and encodes
regular (unicode) strings as ASCII. This function is used in all
places where string literals are meant as bytes, plus all cases where
str() was used to invoke the default conversion of 2.x."""

Very similar to what I expected. However it doesn't answer my question
about how your "move byte strings to a separate file, prepend 'b', and
import the separate file" strategy would help ... and given that 2.5
and earlier will barf on b"arf", I don't expect it to.

> > (2) Assuming supporting only 2.6 and 3.x:
>
> > Suppose you have this line:
> > if binary_data[:4] == "PK\x03\x04": # signature of ZIP file
>
> > Plan A:
> > Change original to:
> > if binary_data[:4] == ZIPFILE_SIG: # "PK\x03\x04"
> > Add this to the bytes section of the separate file:
> > ZIPFILE_SIG = "PK\x03\x04"
> > [somewhat later]
> > Change the above to:
> > ZIPFILE_SIG = b"PK\x03\x04"
> > [once per original file]
> > Add near the top:
> > from separatefile import *
>
> > Plan B:
> > Change original to:
> > if binary_data[:4] == ZIPFILE_SIG: # "PK\x03\x04"
> > Add this to the separate file:
> > ZIPFILE_SIG = b"PK\x03\x04"
> > [once per original file]
> > Add near the top:
> > from separatefile import *
>
> > Plan C:
> > Change original to:
> > if binary_data[:4] == b"PK\3\4": # signature of ZIP file
>
> > Unless I'm gravely mistaken, you seem to be suggesting Plan A or some
> > variety thereof -- what advantages do you see in this over Plan C?
>
> For 2.6 only (which is much easier than 2.x), do C.  Plan A is for 2.x
> where C does not work.

Excuse me? I'm with the OP now, I'm totally confused. Plan C is *not*
what you were proposing; you were proposing something like Plan A
which definitely involved a separate file.

Why won't Plan C work on 2.x (x <= 5)? Because the 2.X will b"arf".
But you say Plan A is for 2.x -- but Plan A involves importing the
separate file which contains and causes b"arf" also!

To my way of thinking, one obvious DISadvantage of a strategy that
actually moves the strings to another file (requiring invention of a
name for each string (that doesn't have one already) so that it can be
imported is the amount of effort and exposure to error required to get
the same functional result as a strategy that keeps the string in the
same file ... and this disadvantage applies irrespective of what one
does to the string: b"arf", Martin's b("arf"), somebody else's _b
("arf") [IIRC] or my you-aint-gonna-miss-noticing-this-in-the-code
BYTES_LITERAL("arf").

Cheers,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-18 Thread andrew cooke
Since this is a PyPy bashing thread, maybe it's an appropriate place
to suggest that the project has got a little bit waylaid by exploring
cool things instead of releasing a useful final result?

I am not questioning rpython directly - the case for something like
that is obvious.  But there's a question of balance.  It's possible to
go on building ever more complex systems which are theoretically
justified, but which postpone ever finishing the job.  At some point
there has to be a "good enough".

To some extent I am playing devil's advocate here, but as an outside
who looked at PyPy a while back, my uninformed and naive impression
was that the project was suffering from the kid of issues I have
caricatured above

Andrew

PS I guess you are aware of worse is better etc?  I think this may
also be a US/Euro culture issue...
--
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic module import?

2009-01-18 Thread alex23
On Jan 17, 3:55 pm, Steven D'Aprano  wrote:
> Both very good points, but consider that you're not comparing apples with
> apples.
>
> >>> __import__("os", fromlist=["system"])
>  >>> system
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'system' is not defined

I must confess I've rarely had a need to use __import__ and don't
think I've ever used the fromlist arg. I'm confused, though, because
the docstring states:

 The fromlist should be a list of names to emulate ``from name
import ...''

But it also states that __import__ always returns a module, so I'm
utterly confused as to the purpose of fromlist, or how to inject the
specified entries into the calling namespace. If anyone could explain
this for me, I'd really appreciate it.

> I mention this only to be pedantic, because I agree with your point that
> exec can introduce security issues, and be significantly slower.

Correcting misinformation isn't pedantry, especially when I've learned
something :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic Loading Modules

2009-01-18 Thread Laszlo Nagy

Riley Porter írta:

Hello all,

This is the first time I have posted to this group.  That being said 
if I am in the wrong place for this kind of support please let me know. 


OK,

So I am writing a log parsing program and wish to allow for the 
community to write "parsers".  Basically, what I have in place now is 
a "modules" directory that contains .py files that are going to be 
used to parse specific log types. 

The question is, is there a way to dynamically import whatever is in 
that modules directory and make is to the import name is actually the 
file name..
So after the modules directory is 'os.listdir' and it returns a 
listing of modules (actually just .py files) IE: ng1-fw.py, 
cisco_asa_fw.py, etc... I can just in the next line of code call:


ng1-fw.Parse(long_file)  #assuming the ng1-fw.py file has a Parse Function

right now using imp I got it to where i can say like:
x =  imp.load_source(md5.new(code_path).hexdigest(), code_path, f)  
#assuming that I gave it the path and filename for ng1-fw.py

I can do this:

x.Parse(log_file)

But what I am really after is the ability to do this:
ng1-fw.Parse(log_file) 

The reason again behind this is so that there is no need to "hard 
code" parser file names. 

Did I make myself clear?  Please let me know if I need to explain that 
better.

What you need is the imp module:

http://docs.python.org/library/imp.html

This module provides an interface to the mechanisms used to implement 
the import  
statement. It defines the following constants and functions:



You might find that using classes instead of modules is more handy.

Regards,

  Laszlo


--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
> Therefore, Python requires you to rewrite the code in some other way
> that makes your intentions more clear. For instance, why not use the
> << operator instead?

Right, but you're guessing what the context is.  Within a DSL it often
makes a lot of sense to use operators for reasons that weren't
originally intended.

You even make the same case yourself indirectly.  The same argument
you make could be made to say that << should only operator on values
that can be shifted.  Now thankfully there is no way to test for that,
so there is no restriction and, consequently, it is now widely
accepted that no-one (even people arguing the case for constraints!)
think it odd to use << for something other than its initial use.

Obviously this kind of discussion has gone on since languages were
first invented - it's the "how much rope" argument.  So rather than
continue down that road I would just like to say that this feels like
an inconsistency.  The other operators are *not* as restricted and
this is making my life harder.

It may sound crazy, but this may force me to use * and ** instead (the
context is a language feature related to *args and **kargs, so the *
and ** help convey the meaning).  And they have a much much stronger
meaning to users, which will make my DSL harder to understand.  So in
this case a blunt knife is making life harder.

Andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread Chris Rebert
On Sun, Jan 18, 2009 at 2:56 AM, andrew cooke  wrote:
> Context - http://docs.python.org/3.0/reference/datamodel.html?highlight=data
> model#object.__iadd__
>
> Just a suggestion I thought I'd throw out...  There's a restriction in
> the language implementation on exactly what can go the left of an
> augmented arithmetic expression.
>
> For example:
 a = 3
 a **= 2
>
> is ok, but:
 class Foo():
> ...   def __init__():
> ... self.a = 3
> ...   def __ipow__(self, x):
> ... self.a **= x
> ...
 Foo() **= 2
>  File "", line 1
> SyntaxError: illegal expression for augmented assignment
>
> Now unless I've done something stupid above (always a possibility :o)
> the implementation seems a bit strict (is it really a *syntax* error?
> - I am not sure exactly what the restriction is).

IIRC, you can only assign to:
- variables (x = ...)
- attributes (x.y = ...)
- elements (x[y] = ...)

Anything else doesn't make sense to assign to because it's not a
"storage box" so to speak. There's no way to work out what is meant.
In your case, you're assigning to a *value*, specifically a new
instance of the Foo class, which is nonsensical; instead of a "box",
you're trying to assign to a "value", something that gets stored in
boxes. By comparison, '2 = 5' and '[1,2] = 7' would seem to have some
sort of meaning under your system, which IMHO seems preposterous.
Now true, you are using augmented assignment, which in certain cases
is translated to a method call, but in principle the augmented
assignment (e.g. x += y) should have roughly the same effect as the
non-augmented equivalent (x = x + y), and the fact that a method call
is involved is merely an implementation detail of sorts.
Therefore, Python requires you to rewrite the code in some other way
that makes your intentions more clear. For instance, why not use the
<< operator instead?

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic module import?

2009-01-18 Thread James Stroud

Lawson Hanson wrote:


So is there any way to get Python to import the named module
without just doing "from dummy import *", because I will
not know that the user wants to use the "dummy" module
until run-time ... I'm trying to import control data
for different run scenarios which will be defined in
differently named Python modules which the user will
specify at run-time with a command-line option

And help with this would be most appreciated


For the sake of humanity, I must try to talk you out of this. Well, it's 
not that serious, but dynamic import confuses programs that inspect code 
like py2exe, etc. I think it is likely that you will find the day that 
you regret trying so hard to 'import *' dynamically. A more maintainable 
way is to simply map the command line argument to an import statement 
and keep your namespaces clean:


"""importer_module"""
import sys
import dummy
import bonafide
modules = {"dummy" : dummy, "bonafide" : bonafide}
module = modules[sys.argv[1]]


If you have several modules that themselves might need the conditional 
imports, simply put the import statements in a separate module (e.g. 
"importer_module" and do something like



"""another_module"""
from importer_module import module


If you simply don't want to import a bunch of modules, use an if/then 
statement. In any event, I advise you to not design your code or usage 
around dynamic imports using the __import__() statement or exec().


James



--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com
--
http://mail.python.org/mailman/listinfo/python-list


Relax Syntax for Augmented Arithmetic?

2009-01-18 Thread andrew cooke
Context - http://docs.python.org/3.0/reference/datamodel.html?highlight=data
model#object.__iadd__

Just a suggestion I thought I'd throw out...  There's a restriction in
the language implementation on exactly what can go the left of an
augmented arithmetic expression.

For example:
>>> a = 3
>>> a **= 2

is ok, but:
>>> class Foo():
...   def __init__():
... self.a = 3
...   def __ipow__(self, x):
... self.a **= x
...
>>> Foo() **= 2
  File "", line 1
SyntaxError: illegal expression for augmented assignment

Now unless I've done something stupid above (always a possibility :o)
the implementation seems a bit strict (is it really a *syntax* error?
- I am not sure exactly what the restriction is).

This may seems like a small issue, but operators can really help with
making embedded DSLs in Python - they give quite a bit of "wiggle
room" to invent a syntax that is compact and intuitive.  The
restriction above cuts into that (OK, so it's still a small
issue... :o)

Cheers,
Andrew
--
http://mail.python.org/mailman/listinfo/python-list


Re: tp_base, ob_type, and tp_bases

2009-01-18 Thread Carl Banks
On Jan 17, 8:12 am, Jeff McNeil  wrote:
> On Jan 17, 11:09 am, Jeff McNeil  wrote:
>
>
>
> > On Jan 17, 10:50 am, "Martin v. Löwis"  wrote:
>
> > > > So, the documentation states that ob_type is a pointer to the type's
> > > > type, or metatype. Rather, this is a pointer to the new type's
> > > > metaclass?
>
> > > That's actually the same. *Every* ob_type field points to the object's
> > > type, e.g. for strings, integers, tuples, etc. That includes type
> > > objects, where ob_type points to the type's type, i.e. it's meta-type,
> > > also called metaclass (as "class" and "type" are really synonyms).
>
> > > > Next, we have tp_base.  That's defined as "an optional pointer to a
> > > > base type from which type properties are inherited."  The value of
> > > > tp_base is then added to the tp_bases tuple.  This is confusing me. On
> > > > the surface, it sound as though they're one in the same?
>
> > > (I don't understand the English "one in the same" - interpreting it
> > > as "as though they should be the same")
>
> > > No: tp_bases is a tuple of all base types (remember, there is multiple
> > > inheritance); tp_base (if set) provides the first base type.
>
> > > > I *think* (and dir() of a subclass of type seems to back it up), that
> > > > tp_base is only at play when the object in question inherits from
> > > > type?
>
> > > No - it is the normal case for single inheritance. You can leave it
> > > NULL, which means you inherit from object.
>
> > > Regards,
> > > Martin
>
> > Thank you! It was tp_base that was confusing me.  The tp_bases member
> > makes sense as Python supports multiple inheritance.  It wasn't
> > immediately clear that tp_base is there for single inheritance
> > reasons. It's all quite clear now.
>
> > Is that an optimization of sorts?
>
> Well, maybe not specifically for single inheritance reasons, I just
> didn't see an immediate reason to keep a separate pointer to the first
> base type.


The reason you need a separate tp_base is because it doesn't
necessarily point to the first base type; rather, it points to the
first base type that has added any fields or slots to its internal
layout (in other words, the first type with a tp_basicsize > 8, on 32-
bit versions).  I believe this is mainly for the benefit of Python
subclasses that define their own slots.  The type constructor will
begin adding slots at an offset of tp_base->tp_basicsize.

To see an example, int objects have a tp_basicsize of 12 (there are 4
extra bytes for the interger).  So if you multiply-inherit from int
and a Python class, int will always be tp_base.

class A(object): pass

class B(int,A): pass
print B.__base__ # will print 

class C(A,int): pass
print C.__base__ # will print 


A related issue is that you can't multiply inherit from two types that
have tp_basicsize > 8 unless one of them inherits from the other.
There can be only one tp_base.  For instance:

class D(int,tuple): pass # will raise TypeError

class E(object):
__slots__ = ['a','b']

class F(object):
__slots__ = ['c','d']

class G(E,G): pass # will raise TypeError

class H(E,int): pass  # will raise TypeError



Here's a bit more background (and by "a bit" I mean "a lot"):

In 32-bit Python, objects of types defined in Python are usually only
16 bytes long.  The layout looks like this.

instance dict
weak reference list
reference count
ob_type

The reference count, which is always the thing that the actual
PyObject* points at, isn't actually the first item in the object's
layout.  The dict and weakref list are stored at a lower address.
(There's a reason for it.)

If a Python class defines any __slots__, the type constructor will add
the slots to the object's layout.

instance dict (if there is one)
weak reference list (if there is one)
reference count
ob_type
slot
slot
slot

Note that, because you defined __slots__, the object might not have an
instance dict or weak reference list associated with it.  It might,
though, if one of the base classes had defined an instance dict or
weakref list.  Or, it might not, but then a subclass might have its
onw instance dict or weakref list.  That's why these guys are placed
at a lower address: so that they don't interfere with the layout of
subclasses.  A subclass can add either more slots or a dict.

Object of types defined in C can have arbitrary layout.  For instance,
it could have a layout that looks like this:

reference count
ob_type
PyObject* a
PyObject* b
long c
float d
instance dict

A problem with Python slots and C fields is that, if you want to
inherit from a type with a non-trivial object layout, aside from the
dict and weakrefs, all of the subtypes have to maintain the same
layout (see Liskov substitutability for rationale).

Subtypes can add their own fields or slots if they want, though.  So,
if a Python subtype wants to define its own slots on top of a type
with a non-trivial object layout, it has to know which base has the
largest layout so that it doesn't use the same memory for

Re: reading file to list

2009-01-18 Thread Xah Lee
On Jan 17, 10:25 am, Tino Wildenhain  wrote:
> > [[int(x) for x in line.split()] for line in open("blob.txt")]

Nice (python code).

Few comments:

• the above code is borderline of atypical. e.g. it is not a average
python code would produce or one'd seen in corporate python code.

• voodoo like the above makes me dislike python. To me, the one
advantage of python is its clarity enforced by its syntax.
Specifically, the forced indendation and quite simple semantics.
However, the way i've seen Guido's propensities and how python 3 is
moving to, it is becoming more mumbo jumbo of computer sciency OOP
jargons with syntax soup. (with iterators, enumerators, list
comprehension... shits forced upon the users)

The above line illustrate well the ad hoc syntax soup nature python is
moving into.

Further readings:

• Perl-Python Tutorial: List Comprehension
  http://xahlee.org/perl-python/list_comprehension.html

• Lambda in Python 3000
  http://xahlee.org/perl-python/python_3000.html

  Xah
∑ http://xahlee.org/

☄
--
http://mail.python.org/mailman/listinfo/python-list


<    1   2