Re: Dynamic variable creation from string

2011-12-12 Thread alex23
On Dec 8, 3:09 am, Massi  wrote:
> in my script I have a dictionary whose items are couples in the form
> (string, integer values), say
>
> D = {'a':1, 'b':2, 'c':3}
>
> This dictionary is passed to a function as a parameter, e.g. :
>
> def Sum(D) :
>     return D['a']+D['b']+D['c']
>
> Is there a way to create three variables dynamically inside Sum in
> order to re write the function like this?
>
> def Sum(D) :
>     # Here some magic to create a,b,c from D
>     return a+b+c

Okay, here's a possible solution that doesn't rely on exec, but does
use the third-party module byteplay (which I believe limits it to
Python 2.5-2.7) and tries to retain as much as possible your syntax
(with some slight adjustments):

from byteplay import Code, opmap

class VariableInjector(dict):
def transmute(self, opcode, arg):
if (opcode == opmap['LOAD_GLOBAL']) and (arg in self):
self._transmuted.append(arg)
return opmap['LOAD_FAST'], arg
return opcode, arg

def make_locals(self, args):
locals = []
for arg in args:
locals.append((opmap['LOAD_CONST'], self[arg]))
locals.append((opmap['STORE_FAST'], arg))
return locals

def bind_to(self, function):
function.ofunc_code = function.func_code
def _(*args, **kwargs):
self._transmuted = []
code = Code.from_code(function.ofunc_code)
code.code = [self.transmute(op, arg) for op, arg in
code.code]
code.code = self.make_locals(self._transmuted) +
code.code
function.func_code = code.to_code()
return function(*args, **kwargs)
return _

For your example, you'd use it like this:

>>> def sum():
... return a + b + c
...
>>> def product():
... return a * b * c
...
>>> data = VariableInjector(a=1,b=2,c=3)
>>> sum = data.bind_to(sum)
>>> product = data.bind_to(product)
>>> sum()
6
>>> product()
6
>>> data
{'a': 1, 'c': 3, 'b': 2}
>>> data['a'] = 100
>>> sum()
105
>>> product()
600

I'm not sure how rigorous this would be in real use but it's passed
the few quick toy cases I've tried it out on.

Any thanks should go to Michael Foord, as this borrows heavily from
his self-less metaclass example:
http://www.voidspace.org.uk/python/articles/metaclasses.shtml
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Gregory Ewing

Steven D'Aprano wrote:

Modulo is hardly an obscure operation. "What's the remainder...?" is a 
simple question that people learn about in primary school.


Well, sort of. The way I remember it, the remainder was just
something that fell out as a side effect of division -- the
annoying bit left over that you didn't know what to do with.
We weren't taught to think of "finding the remainder" as
a distinct operation that's useful in its own right. Once
we were taught to do proper division with decimal points
and everything, the concept of a remainder seemed to get
discarded and was never mentioned again.

A couple of years later we were briefly introduced to the
concept of modulo arithmetic, but as far as I remember, the
connection with division and remainders wasn't pointed out.
Also, it was presented in a very abstract way, and I couldn't
see any practical application for it at the time. (At that
age, it hadn't occurred to me that some of the stuff we
were being shown might be just pure mathematics for its own
sake, and I was often thinking to myself, "Why am I being
taught this?")

It wasn't until much later when I got into programming that
I began to see all the connections and applications. For
people who don't become programmers, I suspect they never
have much use for remainders in everyday life.

Now, in a desperate attempt to stop rambling and get back
on topic...


Eelco Hoogendoorn wrote:

The dot is clearly quantitatively in another realm here.


Also it has almost unchallenged supremacy as the attribute
access operator in just about every language having some
form of struct concept, going back to around Algol 68.
Spelling of the mod operator is much more variable.

{'COMMENT': 24, 'DEDENT': 29, 'NL': 46, 'NAME': 256, "':'": 30, 
'NEWLINE': 83, "'-'": 1, 'NUMBER': 1, "'['": 1, "','": 17, "')'": 37, 
"'('": 37, "'%'": 2, "'.'": 48, "'=='": 1, "'*'": 1, 'INDENT': 29, "']'": 
1, "'='": 28, 'ENDMARKER': 1, 'STRING': 19}


That gives attribute access being a little less than 7% of the source 
code.


However, it's clearly the most commonly used *operator* by
a large margin.


The dot can be easily mistaken for a comma,


Not in my code, because I always put a space after a comma,
and never after an attribute-access dot. (And if you can't
tell whether there's a space there or not, you need a
bigger font or better glasses. :-)

Also, dots sit nicely under my little finger where they're
easy to type. I like dots. Dots are a great goodness.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Gregory Ewing

For what it's worth, googling for "python asterisk"
gives this as the very first result:

  http://www.technovelty.org/code/python/asterisk.html

which tells you exactly what you're probably wanting
to know if you ask that.

To check that this phenomemon isn't restricted to
asterisks in particular, I also tried "python plus
equals" and got

  http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python

which is also a pretty good result.

So the rule of thumb seems to be: if you're trying to
google for punctuation, try spelling it out.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/11/2011 6:53 PM, Eelco Hoogendoorn wrote:

There are other means of finding information than Google. Really.


This is really only a very minor point in my argument, so I dont want to
put the focus on this.


On the contrary, it is a major point. You want us to change the language 
so you can program by Google. Sorry, aint't gonna happen.



Googling 'myprogramminglanguage conceptimtryingtofigureout' is my first,
second and third line of defence. Yes, I could read the reference manual
from top to bottom, and if I already knew about the existence of your
article then im sure that would be a great help too.


You left out skimming the table of contents and using the index. On the 
Windows version of the docs, one can just type the entry wanted in the 
entry box on the Index tab and the lookup is done for you. Two chars to 
type for '**'.



But the situation
one finds oneself in is seeing two asterikses and not even being aware
they are particular to function definitions/invocations.


If you find a symbol in a particular context, the entry for the context 
seems a reasonable place to start.


--
Terry Jan Reedy

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/11/2011 6:44 PM, Eelco Hoogendoorn wrote:


Can you come up with some terse symbols that will be able to express all
of the below and dont make you wish you hadnt rather typed out the names?

head, tuple(tail) = iterable
head, list(tail) = iterable
head, str(tail) = somestring
head, generator(tail) = mygenerator


The above examples are seldom needed in Python because we have one 
general method to repeatedly split a sequence into head and tail.


it = iter(iterable) # 'it' now represents the sequenced iterable
head = next(it) # 'it' now represents the tail after removing the head

In other words, next(it) encompasses all of your examples and many more.
Because 'it' is mutated to represent the tail, it does not need to be 
rebound and therefore is not.


Iterable unpacking with a *target for leftovers is an entirely different 
use case.


--
Terry Jan Reedy

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


Re: I love the decorator in Python!!!

2011-12-12 Thread Ethan Furman

alex23 wrote:

On Dec 9, 8:08 pm, Robert Kern  wrote:

On 12/9/11 5:02 AM, alex23 wrote:

The 3rd party 'decorator' module takes care of issues like docstrings
&  function signatures. I'd really like to see some of that
functionality in the stdlib though.

Much of it is:

   http://docs.python.org/library/functools#functools.update_wrapper


Ah, cheers :) Is that a recent addition? The lack of note makes it
seem like it was there from the beginning?


Not sure how recent it is, but I do know it does *not* handle the signature.

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


Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco Hoogendoorn

 The above examples are seldom needed in Python because we have one
 general method to repeatedly split a sequence into head and tail.



 it = iter(iterable) # 'it' now represents the sequenced iterable
 head = next(it) # 'it' now represents the tail after removing the head



 In other words, next(it) encompasses all of your examples and many more.
 Because 'it' is mutated to represent the tail, it does not need to be
 rebound and therefore is not.



The question in language design is never 'could we do these things 
before'. The answer is obvious: yes our CPUs are turing complete; we can 
do anything. The question is; how would we like to do them?


So do you think the new head/tail unpacking features in python 3 are 
entirely uncalled for? I personally quite like them, but I would like 
them to be more general.

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


Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco Hoogendoorn

> No more, or less, explicit than the difference between "==" and "is".

== may be taken to mean identity comparison; 'equals' can only mean one 
thing. Of course 'formally' these symbols are well defined, but so is 
brainf*ck



 Modulo is hardly an obscure operation. "What's the remainder...?" is a
 simple question that people learn about in primary school.



So is 'how much wood would a woodchucker chuck if a woodchucker could 
chuck wood?'. But how often does that concept turn up in your code?


> And you can blame C for the use of % instead of mod or modulo.

I didnt know one of Python's design goals was backwards compatibility 
with C.



 I can't imagine what sort of Python code you have seen that you consider
 90% attribute access "typical". I've just run the Python tokenizer over
 my startup.py file, and I get these results:


Yes, that was a hyperbole; but quite an often used construct, is it not?


 If you can supply any function at all, what happens if I write this:



You cannot; only constructors modelling a sequence or a dict, and only 
in that order. Is that rule clear enough?


> I believe that your proposal leads to an over-generalisation "call
> arbitrary functions when handling parameter lists".

I hope the above clears that up. It is as much about calling functions 
as ** is about raising kwargs to the power of.


> I don't believe you
> need this added complication. If you want to your var args as a list,
> call list(args) inside your function.

We dont strictly 'need' any language construct. Real men use assembler, 
right?




 >/  head, tuple(tail) = iterable

/>  In Python 3, that is spelled:

 head, *tail = iterable
 tail = tuple(tail)


Yes, I know. How is that not a lot more verbose and worse than what I 
have proposed in all possible ways?


> head, tail = somestring[0], somestring[1:]

Well yes, splendid; we can do that with lists too since the dawn of 
Python. What you are saying here in effect is that you think the 
head/tail syntax is superfluous; that youd rather see it eliminated than 
generalized.


> head, tail = next(mygenerator), mygenerator

Which again of course works, but is yet again of entirely different form 
than any of the above solutions, while conceptually doing the same 
thing. Certainly, there is room for improved elegance here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco Hoogendoorn

 On the contrary, it is a major point. You want us to change the language
 so you can program by Google. Sorry, aint't gonna happen.


On the contrary; I believe I get to decide which points I consider 
important. This one, I do not. Sorry for putting it in the first paragraph.

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


Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco Hoogendoorn

> On the contrary, it is a major point.

Sorry, but im affraid it is up to ME to decide which point I feel are 
important. No, this is a minor point to me, and one that has been 
admirably put to rest by pointing out that spelling out the name of the 
symbol in google directly leads you to the information you are looking for.

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


Re: unittest. customizing tstloaders / discover()

2011-12-12 Thread Thomas Bach
Gelonida N  writes:

> Do I loose anything if using nose. or example can all unit tests / doc
> tests still be run from nose?

AFAIK you don't loose anything by using nose – the unittests should all
be found and doctests can be run via `--with-doctest', I never used
doctests though.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Jussi Piitulainen
Eelco Hoogendoorn writes:

> As for %; it is entirely unclear to me why that obscure operation
> ever got its own one-character symbol. Ill take 'mod', or even
> better, 'modulus' any day of the week.

The modulus is not the result but one of the arguments: when numbers x
and y are congruent modulo n (stated in terms of the modulo operation:
x mod n = y mod n), the modulus is n. A word for x mod n is remainder.

I agree about the obscurity of using the percent sign as the operator.

A quick google suggests that your use of 'modulus' is now popular
among programmers. Past experience in mathematics newsgroups tells me
that some mathematicians do not accept the existence of any remainder
operator at all. Honest. (I see them but I cannot understand them.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding a global

2011-12-12 Thread Jean-Michel Pichavant

Roy Smith wrote:

MRAB  wrote:

  

or use 'globals':

 def function(self):
 logger = globals()['logger'].getChild('function')
 logger.debug('stuff')
 logger.debug('other stuff')



Ah-ha!  That's precisely what I was looking for.  Much appreciated.
  

Using the same name for 2 different objects is a bad idea in general.
In debug mode, i.e. the logger is configured with the debug level, you 
could simply write down the filename and the line number on your log 
events.


formatter = logging.Formatter('%(name)s : %(filename)s %(lineno)s  
%(message)s')


So you can easily see who logged what (if I'm not wrong, that's what 
you're trying to do)


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
> The modulus is not the result but one of the arguments: when numbers x
> and y are congruent modulo n (stated in terms of the modulo operation:
> x mod n = y mod n), the modulus is n. A word for x mod n is remainder.
>
> I agree about the obscurity of using the percent sign as the operator.
>
> A quick google suggests that your use of 'modulus' is now popular
> among programmers. Past experience in mathematics newsgroups tells me
> that some mathematicians do not accept the existence of any remainder
> operator at all. Honest. (I see them but I cannot understand them.)

You are correct; the thing it computes is the remainder, not the
modulus. Nonetheless, 'x modulus y' is how it is put in natural
language, but I suppose math.remainder would be my preferred place to
put this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco

By the way...

Is there any particular reason why some of my replies do not show up
on groups.google, and some of them do not show up on mail.python.org?
Sorry to annoy people with reposting, but im going to be forced to do
some of that until this is cleared up
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Jussi Piitulainen
Eelco writes:

> > The modulus is not the result but one of the arguments: when numbers x
> > and y are congruent modulo n (stated in terms of the modulo operation:
> > x mod n = y mod n), the modulus is n. A word for x mod n is remainder.
> >
> > I agree about the obscurity of using the percent sign as the operator.
> >
> > A quick google suggests that your use of 'modulus' is now popular
> > among programmers. Past experience in mathematics newsgroups tells me
> > that some mathematicians do not accept the existence of any remainder
> > operator at all. Honest. (I see them but I cannot understand them.)
> 
> You are correct; the thing it computes is the remainder, not the
> modulus. Nonetheless, 'x modulus y' is how it is put in natural
> language, but I suppose math.remainder would be my preferred place to
> put this.

I think it's 'x modulo y', which matches 'x and y are congruent modulo
z', but now I fear that programming people have been developing a
different habit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I love the decorator in Python!!!

2011-12-12 Thread 88888 Dihedral
On Monday, December 12, 2011 1:47:52 PM UTC+8, alex23 wrote:
> On Dec 12, 2:51 pm, 8 Dihedral 
> wrote:
> > To wrap a function properly is different from the 1-line lampda.
> >
> > This is really functional programming.
> >
> > Every function can be decorated to change into a different one easily.
> >
> > There is  a method to replace every return action  of a python function
> > into an  yield action without the source code.
> 
> How does this have _anything_ to do with my exchange with Robert?
> 
> If you're _not_ a markov chainer, you're trying way too hard to show
> off what you know, and very little of it seems relevant to the thread.

I think in the CS  way in the 5th generation computer languages. 
But I also think in the hardware way in the 2,3,4th generations.

Why do you need to spawn a thread or a process  that can be decorated by 
wrapping  an yield for all kinds of  parameter checking of functions?

A lousy written function in any computer language indicates
a bad taste of art. 

 

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
> No more, or less, explicit than the difference between "==" and "is".

== may be taken to mean identity comparison; 'equals' can only mean
one
thing. Of course 'formally' these symbols are well defined, but so is
brainf*ck

>  Modulo is hardly an obscure operation. "What's the remainder...?" is a
>  simple question that people learn about in primary school.


So is 'how much wood would a woodchucker chuck if a woodchucker could
chuck wood?'. But how often does that concept turn up in your code?

> And you can blame C for the use of % instead of mod or modulo.

I didnt know one of Python's design goals was backwards compatibility
with C.

>  I can't imagine what sort of Python code you have seen that you consider
>  90% attribute access "typical". I've just run the Python tokenizer over
>  my startup.py file, and I get these results:

Yes, that was a hyperbole; but quite an often used construct, is it
not?

>  If you can supply any function at all, what happens if I write this:


You cannot; only constructors modelling a sequence or a dict, and
only
in that order. Is that rule clear enough?

> I believe that your proposal leads to an over-generalisation "call
> arbitrary functions when handling parameter lists".

I hope the above clears that up. It is as much about calling
functions
as ** is about raising kwargs to the power of.

> I don't believe you
> need this added complication. If you want to your var args as a list,
> call list(args) inside your function.

We dont strictly 'need' any language construct. Real men use
assembler,
right?


>  >  head, tuple(tail) = iterable
>  In Python 3, that is spelled:
>  head, *tail = iterable
>  tail = tuple(tail)

Yes, I know. How is that not a lot more verbose and worse than what I
have proposed in all possible ways?

> head, tail = somestring[0], somestring[1:]

Well yes, splendid; we can do that with lists too since the dawn of
Python. What you are saying here in effect is that you think the
head/tail syntax is superfluous; that youd rather see it eliminated
than
generalized.

> head, tail = next(mygenerator), mygenerator

Which again of course works, but is yet again of entirely different
form
than any of the above solutions, while conceptually doing the same
thing. Certainly, there is room for improved elegance here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic variable creation from string

2011-12-12 Thread 88888 Dihedral
On Monday, December 12, 2011 3:11:18 PM UTC+8, alex23 wrote:
> On Dec 8, 3:09 am, Massi  wrote:
> > in my script I have a dictionary whose items are couples in the form
> > (string, integer values), say
> >
> > D = {'a':1, 'b':2, 'c':3}
> >
> > This dictionary is passed to a function as a parameter, e.g. :
> >
> > def Sum(D) :
> >     return D['a']+D['b']+D['c']
> >
> > Is there a way to create three variables dynamically inside Sum in
> > order to re write the function like this?
> >
> > def Sum(D) :
> >     # Here some magic to create a,b,c from D
> >     return a+b+c
> 
> Okay, here's a possible solution that doesn't rely on exec, but does
> use the third-party module byteplay (which I believe limits it to
> Python 2.5-2.7) and tries to retain as much as possible your syntax
> (with some slight adjustments):
> 
> from byteplay import Code, opmap
> 
> class VariableInjector(dict):
> def transmute(self, opcode, arg):
> if (opcode == opmap['LOAD_GLOBAL']) and (arg in self):
> self._transmuted.append(arg)
> return opmap['LOAD_FAST'], arg
> return opcode, arg
> 
> def make_locals(self, args):
> locals = []
> for arg in args:
> locals.append((opmap['LOAD_CONST'], self[arg]))
> locals.append((opmap['STORE_FAST'], arg))
> return locals
> 
> def bind_to(self, function):
> function.ofunc_code = function.func_code
> def _(*args, **kwargs):
> self._transmuted = []
> code = Code.from_code(function.ofunc_code)
> code.code = [self.transmute(op, arg) for op, arg in
> code.code]
> code.code = self.make_locals(self._transmuted) +
> code.code
> function.func_code = code.to_code()
> return function(*args, **kwargs)
> return _
> 
> For your example, you'd use it like this:
> 
> >>> def sum():
> ... return a + b + c
> ...
> >>> def product():
> ... return a * b * c
> ...
> >>> data = VariableInjector(a=1,b=2,c=3)
> >>> sum = data.bind_to(sum)
> >>> product = data.bind_to(product)
> >>> sum()
> 6
> >>> product()
> 6
> >>> data
> {'a': 1, 'c': 3, 'b': 2}
> >>> data['a'] = 100
> >>> sum()
> 105
> >>> product()
> 600
> 
> I'm not sure how rigorous this would be in real use but it's passed
> the few quick toy cases I've tried it out on.
> 
> Any thanks should go to Michael Foord, as this borrows heavily from
> his self-less metaclass example:
> http://www.voidspace.org.uk/python/articles/metaclasses.shtml

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


Re: Dynamic variable creation from string

2011-12-12 Thread 88888 Dihedral
On Monday, December 12, 2011 3:11:18 PM UTC+8, alex23 wrote:
> On Dec 8, 3:09 am, Massi  wrote:
> > in my script I have a dictionary whose items are couples in the form
> > (string, integer values), say
> >
> > D = {'a':1, 'b':2, 'c':3}
> >
> > This dictionary is passed to a function as a parameter, e.g. :
> >
> > def Sum(D) :
> >     return D['a']+D['b']+D['c']
> >
> > Is there a way to create three variables dynamically inside Sum in
> > order to re write the function like this?
> >
> > def Sum(D) :
> >     # Here some magic to create a,b,c from D
> >     return a+b+c
> 
> Okay, here's a possible solution that doesn't rely on exec, but does
> use the third-party module byteplay (which I believe limits it to
> Python 2.5-2.7) and tries to retain as much as possible your syntax
> (with some slight adjustments):
> 
> from byteplay import Code, opmap
> 
> class VariableInjector(dict):
> def transmute(self, opcode, arg):
> if (opcode == opmap['LOAD_GLOBAL']) and (arg in self):
> self._transmuted.append(arg)
> return opmap['LOAD_FAST'], arg
> return opcode, arg

> 
> def make_locals(self, args):
> locals = []
> for arg in args:
> locals.append((opmap['LOAD_CONST'], self[arg]))
> locals.append((opmap['STORE_FAST'], arg))
> return locals
> 
> def bind_to(self, function):
> function.ofunc_code = function.func_code
> def _(*args, **kwargs):
> self._transmuted = []
> code = Code.from_code(function.ofunc_code)
> code.code = [self.transmute(op, arg) for op, arg in
> code.code]
> code.code = self.make_locals(self._transmuted) +
> code.code
> function.func_code = code.to_code()
> return function(*args, **kwargs)
> return _
> 
> For your example, you'd use it like this:
> 
> >>> def sum():
> ... return a + b + c
> ...
> >>> def product():
> ... return a * b * c
> ...
> >>> data = VariableInjector(a=1,b=2,c=3)
> >>> sum = data.bind_to(sum)
> >>> product = data.bind_to(product)
> >>> sum()
> 6
> >>> product()
> 6
> >>> data
> {'a': 1, 'c': 3, 'b': 2}
> >>> data['a'] = 100
> >>> sum()
> 105
> >>> product()
> 600
> 
> I'm not sure how rigorous this would be in real use but it's passed
> the few quick toy cases I've tried it out on.
> 
> Any thanks should go to Michael Foord, as this borrows heavily from
> his self-less metaclass example:
> http://www.voidspace.org.uk/python/articles/metaclasses.shtml

This is the way to write an assembler or 
to roll out a script language to be included in an app
by users. 

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


Confusion about decorators

2011-12-12 Thread Henrik Faber
Hi group,

I'm a bit confused regarding decorators. Recently started playing with
them with Python3 and wanted (as an excercise) to implement a simple
type checker first: I know there are lots of them out there, this is
actually one of the reasons I chose that particular function (to compare
my solution against other, proven solutions).

Starting with a blank slate, I did something along the lines of:

class _TypeCheckedFunction():
def __init__(self, decoratedfunction):
self._decoratedfunction = decoratedfunction

def __call__(self, *args, **kwargs):
[...] Actual checking

def typecheck(wrappedfunction):
checkfunction = _TypeCheckedFunction(wrappedfunction)
functools.update_wrapper(checkfunction, wrappedfunction)
return checkfunction

And decorate my methods like

@typecheck
def setbar(self, bar: str):

This works somewhat. The problem is, however, when the method is
actually called. This is what happens:

1. The decorator is called upon import of the decorated class. It
creates a _TypeCheckedFunction(setbar) object.
2. When setbar is actually called (blubb.setbar("fooobar")), the
__call__ method of the previously created _TypeCheckedFunction is invoked.
3. When trying to call self._decoratedfunction from within that object,
this fails: "self" is missing! self._decoratedfunction is only the
*function*, not the bound function of the object that contains setbar().
Therefore I cannot proceed here.

Solutions that I have seen working usually consist of two functions
wrapped in each other, but I do not know why the additional introduction
of a class makes everything fail.

Can someone please enlighten me?

Best regards,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion about decorators

2011-12-12 Thread Andrea Crotti

On 12/12/2011 01:27 PM, Henrik Faber wrote:

Hi group,

I'm a bit confused regarding decorators. Recently started playing with
them with Python3 and wanted (as an excercise) to implement a simple
type checker first: I know there are lots of them out there, this is
actually one of the reasons I chose that particular function (to compare
my solution against other, proven solutions).

Starting with a blank slate, I did something along the lines of:

class _TypeCheckedFunction():
def __init__(self, decoratedfunction):
self._decoratedfunction = decoratedfunction

def __call__(self, *args, **kwargs):
[...] Actual checking

def typecheck(wrappedfunction):
checkfunction = _TypeCheckedFunction(wrappedfunction)
functools.update_wrapper(checkfunction, wrappedfunction)
return checkfunction

And decorate my methods like

@typecheck
def setbar(self, bar: str):

This works somewhat. The problem is, however, when the method is
actually called. This is what happens:

1. The decorator is called upon import of the decorated class. It
creates a _TypeCheckedFunction(setbar) object.
2. When setbar is actually called (blubb.setbar("fooobar")), the
__call__ method of the previously created _TypeCheckedFunction is invoked.
3. When trying to call self._decoratedfunction from within that object,
this fails: "self" is missing! self._decoratedfunction is only the
*function*, not the bound function of the object that contains setbar().
Therefore I cannot proceed here.

Solutions that I have seen working usually consist of two functions
wrapped in each other, but I do not know why the additional introduction
of a class makes everything fail.

Can someone please enlighten me?

Best regards,
Henrik


Not sure how that could work in general, what does "bar: str" should do?
Is that a dictionary?

Anyway there is already an implementation if you're interested for type 
checking:

http://oakwinter.com/code/typecheck/

You can have a look at how they do it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion about decorators

2011-12-12 Thread Arnaud Delobelle
On 12 December 2011 13:27, Henrik Faber  wrote:
> Hi group,
>
> I'm a bit confused regarding decorators. Recently started playing with
> them with Python3 and wanted (as an excercise) to implement a simple
> type checker first: I know there are lots of them out there, this is
> actually one of the reasons I chose that particular function (to compare
> my solution against other, proven solutions).
>
> Starting with a blank slate, I did something along the lines of:
>
> class _TypeCheckedFunction():
>        def __init__(self, decoratedfunction):
>                self._decoratedfunction = decoratedfunction
>
>        def __call__(self, *args, **kwargs):
>                [...] Actual checking
>
> def typecheck(wrappedfunction):
>        checkfunction = _TypeCheckedFunction(wrappedfunction)
>        functools.update_wrapper(checkfunction, wrappedfunction)
>        return checkfunction
>
> And decorate my methods like
>
>        @typecheck
>        def setbar(self, bar: str):
>
> This works somewhat. The problem is, however, when the method is
> actually called. This is what happens:
>
> 1. The decorator is called upon import of the decorated class. It
> creates a _TypeCheckedFunction(setbar) object.
> 2. When setbar is actually called (blubb.setbar("fooobar")), the
> __call__ method of the previously created _TypeCheckedFunction is invoked.
> 3. When trying to call self._decoratedfunction from within that object,
> this fails: "self" is missing! self._decoratedfunction is only the
> *function*, not the bound function of the object that contains setbar().
> Therefore I cannot proceed here.
>
> Solutions that I have seen working usually consist of two functions
> wrapped in each other, but I do not know why the additional introduction
> of a class makes everything fail.
>
> Can someone please enlighten me?

You can (need to?) use the descriptor protocol to deal with methods.

from functools import partial

class _TypeCheckedFunction():
   def __init__(self, decoratedfunction):
   self._decoratedfunction = decoratedfunction

   def __call__(self, *args, **kwargs):
   [...] Actual checking

   def __get__(self, obj, objtype):
   return partial(self, obj)

(Untested)

HTH

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


Re: Confusion about decorators

2011-12-12 Thread Henrik Faber
On 12.12.2011 14:37, Andrea Crotti wrote:
> On 12/12/2011 01:27 PM, Henrik Faber wrote:
>> Hi group,
>>
>> I'm a bit confused regarding decorators. Recently started playing with
>> them with Python3 and wanted (as an excercise) to implement a simple
>> type checker first: I know there are lots of them out there, this is
>> actually one of the reasons I chose that particular function (to compare
>> my solution against other, proven solutions).
>
> Not sure how that could work in general, what does "bar: str" should do?
> Is that a dictionary?

No. It's PEP 3107 function annotations.

> Anyway there is already an implementation if you're interested for type
> checking:
> http://oakwinter.com/code/typecheck/

*sigh* no, not really -- this is exactly why I wrote "I know there are
lots of them out there". I've actually seen and run
http://code.activestate.com/recipes/577299-method-signature-type-checking-decorator-for-pytho/

However, this doesn't do it for me -- I want to know why my solution
fails, not just use some other solution without really understanding it.
I really would like to understand what's going on.

I'm especially puzzled about the fact that in my solution, __call__ is
called with only the method's arguments (i.e. "fooobar") in my example
instead of two arguments (self, "fooobar").

Best regards,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion about decorators

2011-12-12 Thread Henrik Faber
On 12.12.2011 14:45, Arnaud Delobelle wrote:

>> Can someone please enlighten me?
> 
> You can (need to?) use the descriptor protocol to deal with methods.
>
> from functools import partial
[...]
>def __get__(self, obj, objtype):
>return partial(self, obj)

Whoa. This is absolutely fantastic, it now works as expected (I get a
reference to "self").

I am very amazed -- I've been programming Python for about 5 years now
and have never even come close to something as a "descriptor protocol".
Python never ceases to amaze me. Do you have any beginners guide how
this works? The Pydoc ("Data Model") is comprehensive, but I really
don't know where to start to look.

Still amazed!

Best regards,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion about decorators

2011-12-12 Thread Arnaud Delobelle
On 12 December 2011 13:52, Henrik Faber  wrote:
> On 12.12.2011 14:45, Arnaud Delobelle wrote:
>
>>> Can someone please enlighten me?
>>
>> You can (need to?) use the descriptor protocol to deal with methods.
>>
>> from functools import partial
> [...]
>>        def __get__(self, obj, objtype):
>>                return partial(self, obj)
>
> Whoa. This is absolutely fantastic, it now works as expected (I get a
> reference to "self").
>
> I am very amazed -- I've been programming Python for about 5 years now
> and have never even come close to something as a "descriptor protocol".
> Python never ceases to amaze me. Do you have any beginners guide how
> this works? The Pydoc ("Data Model") is comprehensive, but I really
> don't know where to start to look.

Well, I've been using Python for 10 years :)  The best reference I know is:

http://users.rcn.com/python/download/Descriptor.htm

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


RE: subprocess question

2011-12-12 Thread jyoung79
> import subprocess 
> p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', 
>> stdout=subprocess.PIPE) 
> out, err = p.communicate() 
> out 
>> ' 11M\t.\n' 
 
> You might prefer to use subprocess.check_output(); it slightly 
> simplifies your code: 
> http://docs.python.org/library/subprocess.html#subprocess.check_output 
 
>> And another question - why can't I use the tilde as a shortcut to the home 
>> directory? 
 
> Because ~ is interpolated by the shell and `subprocess` does not use 
> the shell by default for reasons that include efficiency and security. 
> You can expand ~ yourself using os.path.expanduser(): 
> http://docs.python.org/library/os.path.html#os.path.expanduser 
> Alternatively, you can opt to use the shell by passing shell=True as 
> an argument. 
 
> Cheers, 
> Chris 

Thank you very much, Chris and Andrew, for your help.  I appreciate it!  :-)

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


Re: subprocess question

2011-12-12 Thread Nobody
On Sun, 11 Dec 2011 22:02:23 -0800, Chris Rebert wrote:

> p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', 
> stdout=subprocess.PIPE)

> Alternatively, you can opt to use the shell by passing shell=True as
> an argument.

Except that the OP is talking about a directory passed to the cwd=
parameter, rather than as part of the command, and shell= doesn't affect
that.

But even if the directory was part of the command, just setting shell=True
won't work. On Unix (including MacOSX) the call:

subprocess.Popen(['du', '-sh'], shell=True)

is equivalent to:

subprocess.Popen(['/bin/sh', '-c', 'du', '-sh'], shell=False)

This will result in the shell executing "du" with no arguments. The
variable expansion "$1" will evaluate to "-sh", but that's meaningless as
"$1" doesn't occur in the argument to "-c".

The combination of using a list for the "args" parameter along
with shell=True is rarely useful on Unix. And using a string for the
"args" parameter introduces all of the associated reliability and security
issues.

The situation is different on Windows, where list/string and shell= are
orthogonal. A list is always converted to a string according to the
rules by which MSVCRT parses the command line into argv[]. Then, if
shell=True, "cmd.exe /c " is prepended to the string (actually, the value
of the COMSPEC environment variable is used in place of cmd.exe if it is
defined). Setting shell=True allows the "program" to be any file with a
registered extension, rather than just an executable.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/12/2011 3:09 AM, Gregory Ewing wrote:


people who don't become programmers, I suspect they never
have much use for remainders in everyday life.


Huh? Funny you should say 'everyday'. It is now 10 o'clock. In 20 hours, 
it will be (10+20) % 12 == 6 o'clock. It is now day 1 of the week. In 9 
days it will be day (1+9) % 7 == 3 of the week. Mental calculations are 
helped by the fact that (a+b) % c == a%c + b%c, so that would actually 
be 1+2==3. Timekeeping is mostly remaindering, slightly obscured by 
using 12 instead of 0.


--
Terry Jan Reedy

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


Re: Confusion about decorators

2011-12-12 Thread Henrik Faber
On 12.12.2011 15:01, Arnaud Delobelle wrote:

>> I am very amazed -- I've been programming Python for about 5 years now
>> and have never even come close to something as a "descriptor protocol".
>> Python never ceases to amaze me. Do you have any beginners guide how
>> this works? The Pydoc ("Data Model") is comprehensive, but I really
>> don't know where to start to look.
> 
> Well, I've been using Python for 10 years :)  The best reference I know is:
> 
> http://users.rcn.com/python/download/Descriptor.htm

Everyone starts out as a Padawan and I am no exception :-)

Maybe five years from now I'll also have made my way to be a Python Jedi
and also shake the ins and outs of descriptors out of my sleeve :-)

But I can only repeat myself: Python is such an exceptional language,
the more and more I know about it, the more I fall in love! Fantastic. I
wish we had these types of language when I was a kid!

Best regards and thanks again,
Henrik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/12/2011 5:59 AM, Jussi Piitulainen wrote:



Past experience in mathematics newsgroups tells me
that some mathematicians do not accept the existence of any remainder
operator at all.


Even though they carry hour/minute/second remindering devices on their 
bodies and put year/month/day remaindering devices on their wall? 
'Twould be strange indeed!


--
Terry Jan Reedy

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/12/2011 4:12 AM, Eelco Hoogendoorn wrote:

The above examples are seldom needed in Python because we have one
general method to repeatedly split a sequence into head and tail.



it = iter(iterable) # 'it' now represents the sequenced iterable
head = next(it) # 'it' now represents the tail after removing the head



In other words, next(it) encompasses all of your examples and many more.
Because 'it' is mutated to represent the tail, it does not need to be
rebound and therefore is not.



The question in language design is never 'could we do these things
before'. The answer is obvious: yes our CPUs are turing complete; we can
do anything. The question is; how would we like to do them?

So do you think the new head/tail unpacking features in python 3 are
entirely uncalled for?


No, *target unpacking (singular) is quite useful in specialized cases. 
But it is not specifically head/tail unpacking.


>>> a,*b,c = 1,2,3,4,5,6
>>> a,b,c
(1, [2, 3, 4, 5], 6)
>>> *a,b,c = 1,2,3,4,5
>>> a,b,c
([1, 2, 3], 4, 5)


I personally quite like them, but I would like them to be more general.


It already is. The *target can be anywhere in the sequence.

--
Terry Jan Reedy

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Nick Dokos
Terry Reedy  wrote:


> calculations are helped by the fact that (a+b) % c == a%c + b%c, so

As long as we understand that == here does not mean "equal", only
"congruent modulo c", e.g try a = 13, b = 12, c = 7.

Nick






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


multiprocessing module question

2011-12-12 Thread dmitrey
hi all,
suppose I have a func F, list [args1,args2,args3,...,argsN] and want
to obtain r_i = F(args_i) in parallel mode. My difficulty is: if F
returns not None, than I should break calculations, and I can't dig in
multiprocessing module documentation how to do it. Order doesn't
matter for me (I have to find 1st suitable, where result of F is not
None)
Could anyone scribe me an example?
Thank you in advance, D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Arnaud Delobelle
On 12 December 2011 15:52, Terry Reedy  wrote:

> No, *target unpacking (singular) is quite useful in specialized cases. But
> it is not specifically head/tail unpacking.
>
 a,*b,c = 1,2,3,4,5,6
 a,b,c
> (1, [2, 3, 4, 5], 6)
 *a,b,c = 1,2,3,4,5
 a,b,c
> ([1, 2, 3], 4, 5)
>
>> I personally quite like them, but I would like them to be more general.
>
>
> It already is. The *target can be anywhere in the sequence.
>
> --
> Terry Jan Reedy

You can even have nested sequences!

>>> a, (b, *c), *d = 1, "two", 3, 4

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


Wing IDE 4.1.2 released

2011-12-12 Thread Wingware

Hi,

Wingware has released version 4.1.2 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

Wing IDE is a cross-platform Python IDE that provides a professional code
editor with vi, emacs, and other key bindings, auto-completion, call tips,
refactoring, context-aware auto-editing, a powerful graphical debugger,
version control, unit testing, search, and many other features.

**Changes in Version 4.1.2**

Highlights of this release include:

* Added Create New Package to the Project context menu
* Added Open Files tool for navigating to and closing open files
* Added new code selection commands in the Edit > Select menu
  to select current/next/previous statement or scope
* Many auto-editing, auto-indent, and auto-completion improvements
* Fixed evaluation in shells of files with a coding comment
* Several VI mode fixes
* About 15 other bug fixes and minor improvements

Complete change log: http://wingware.com/pub/wingide/4.1.2/CHANGELOG.txt

**New Features in Version 4**

Version 4 adds the following new major features:

* Refactoring -- Rename/move symbols, extract to function/method, and 
introduce variable

* Find Uses -- Find all points of use of a symbol
* Auto-Editing -- Reduce typing burden by auto-entering expected code
* Diff/Merge -- Graphical file and repository comparison and merge
* Django Support -- Debug Django templates, run Django unit tests, and more
* matplotlib Support -- Maintains live-updating plots in shell and debugger
* Simplified Licensing -- Includes all OSes and adds Support+Upgrades 
subscriptions


Details on licensing changes:  http://wingware.com/news/2011-02-16

**About Wing IDE**

Wing IDE is an integrated development environment designed specifically for
the Python programming language.  It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching beginning programming courses with Python.

Version 4.0 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard
  personalities
* Code intelligence for Python:  Auto-completion, call tips, find uses,
  goto-definition, error indicators, refactoring, context-aware 
auto-editing,

  smart indent and rewrapping, and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,

  conditional breakpoints, data value tooltips over code, watch tool, and
  externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical

  UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and

  Perforce
* Integrated unit testing with unittest, nose, and doctest frameworks
* Django support:  Debugs Django templates, provides project setup tools,
  and runs Django unit tests
* Many other features including project manager, bookmarks, code snippets,
  diff/merge tool, OS command integration, indentation manager, PyLint
  integration, and perspectives
* Extremely configurable and may be extended with Python scripts
* Extensive product documentation and How-Tos for Django, matplotlib,
  Plone, wxPython, PyQt, mod_wsgi, Autodesk Maya, and many other frameworks

Please refer to http://wingware.com/wingide/features for a detailed listing
of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later 
(requires
X11 Server), or a recent Linux system (either 32 or 64 bit).  Wing IDE 
supports

Python versions 2.0.x through 3.2.x and Stackless Python.

For more information, see the http://wingware.com/

**Downloads**

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run. A free trial can be obtained directly from the
product when launched.

Wing IDE Pro -- Full-featured product:
http://wingware.com/downloads/wingide/4.1

Wing IDE Personal -- A simplified IDE:
http://wingware.com/downloads/wingide-personal/4.1

Wing IDE 101 -- For teaching with Python:
http://wingware.com/downloads/wingide-101/4.1

**Purchasing and Upgrading**

Wing 4.x requires an upgrade for Wing IDE 2.x and 3.x users at a cost of
1/2 the full product pricing.

Upgrade a license:   https://wingware.com/store/upgrade
Purchase a new license:  https://wingware.com/store/purchase

Optional Support+Upgrades subscriptions are available for expanded
support coverage and free upgrades to new major releases:

http://wingware.com/support/agreem

Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Arnaud Delobelle
On 12 December 2011 15:36, Terry Reedy  wrote:
> Huh? Funny you should say 'everyday'. It is now 10 o'clock. In 20 hours, it
> will be (10+20) % 12 == 6 o'clock. It is now day 1 of the week. In 9 days it
> will be day (1+9) % 7 == 3 of the week. Mental calculations are helped by
> the fact that (a+b) % c == a%c + b%c

You mean (a + b) % c == (a%c + b%c) % c

:)

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Chris Angelico
On Tue, Dec 13, 2011 at 2:55 AM, Nick Dokos  wrote:
> Terry Reedy  wrote:
>> calculations are helped by the fact that (a+b) % c == a%c + b%c, so
>
> As long as we understand that == here does not mean "equal", only
> "congruent modulo c", e.g try a = 13, b = 12, c = 7.

This is the basis of the grade-school "casting out nines" method of
checking arithmetic. Set c=9 and you can calculate N%c fairly readily
(digit sum - I'm assuming here that the arithmetic is being done in
decimal); the sum of the remainders should equal the remainder of the
sum, but there's the inherent assumption that if the remainders sum to
something greater than nine, you digit-sum it to get the true
remainder.

(Technically the sum of the digits of a base-10 number is not the same
as that number mod 9, but if you accept that 0 == 9, it works fine.)

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Chris Angelico
On Tue, Dec 13, 2011 at 3:15 AM, Arnaud Delobelle  wrote:
>
> You mean (a + b) % c == (a%c + b%c) % c
>
> :)

It's just integer wraparound. Modulo 9 is the same as "render this
number in base 9 and take the last digit" (and printing a number in
base 9 would normally be done with mod 9 division), and most people
can wrap their heads around the way an odometer wraps around.

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


Re: I love the decorator in Python!!!

2011-12-12 Thread Robert Kern

On 12/12/11 3:36 AM, alex23 wrote:

On Dec 9, 8:08 pm, Robert Kern  wrote:

On 12/9/11 5:02 AM, alex23 wrote:

The 3rd party 'decorator' module takes care of issues like docstrings
&function signatures. I'd really like to see some of that
functionality in the stdlib though.


Much of it is:

http://docs.python.org/library/functools#functools.update_wrapper


Ah, cheers :) Is that a recent addition? The lack of note makes it
seem like it was there from the beginning?


The module was added in Python 2.5 as noted at the top of the page.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


PyDev and multithreaded application debug

2011-12-12 Thread Massi
Hi everyone, I've just started to use pydev to develop my python
application and I'm encountering some problems to debug it. The
application I'm dealing with is a multithreaded application; when I
try to debug it with pydev, it seems not to be able to handle the
execution of multiple threads. The problem is that when the execution
reaches a breakpoint in one of the threads, all the other ones don't
stop, but they continue their execution.
Have I to make some specific settings or am I missing something?
Thanks in advance!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to module.__file__?

2011-12-12 Thread Robert Kern

On 12/12/11 1:25 AM, MRAB wrote:

On 12/12/2011 00:21, Steven D'Aprano wrote:

I've just started using a Debian system, instead of the usual RedHat
based systems I'm used to, and module.__file__ appears to have
disappeared for some (but not all) modules.

On Fedora:

[steve@orac ~]$ python -E
Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21)
[GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import math
math.__file__

'/usr/lib/python2.6/lib-dynload/mathmodule.so'



and on Debian squeeze:

steve@runes:~$ python -E
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import math
math.__file__

Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no attribute '__file__'


What's going on?


The documentation for __file__ says: """The __file__ attribute is not
present for C modules that are statically linked into the interpreter;
for extension modules loaded dynamically from a shared library, it is
the pathname of the shared library file."""

Interestingly, none of the versions on Windows that I've tried have
that attribute for the math module. Is it platform-dependent?


It is build-dependent. Windows builds typically have math and several other 
stdlib "extension" modules built into the PythonXY.dll . Unix builds typically, 
but apparently not always, leave mathmodule.so and others as separate extension 
modules.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


automate commands to an .exe console program through python

2011-12-12 Thread Juan Perez
Hi,

I'm new to this mailing list and new in python as well.

I need to automate a .exe console program in windows, and send key
characters like 'a', 'M' ... I don't need to take the output as is printed
in a different text log, but I'll have to send the messages to the program.
I had this running in an autoIT script which with only activating cmd
window, and with the "send" parameter I had all already done. But I'm
having a lot of problems with python, I've tried with process.call,
communicate(), os.popen ... but no results. I can't comunicate with the
program and even i can't maintain it opened more than  a few seconds. If I
open a program like notepad.exe it remains opened but when I try to
comunicate with the stdin pipe just don't write anything to the program.

Someone has any idea about that,

Thanks and sorry for my english level,

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


Re: Documentation for python-evolution - where?

2011-12-12 Thread tinnews
Chris Angelico  wrote:
> On Mon, Dec 12, 2011 at 9:28 AM,   wrote:
> > I'm trying to use the python evolution (as in Gnome Evolution) module
> > but I can't find any documetation beyond the odd trivial example and
> > the API documentation at http://doc.conduit-project.org/evolution-python/
> > (or similar places presumably).
> 
> One of the downsides of software you don't pay money for is that, all
> too often, there's little or no documentation. One of the upsides of
> free software is that you can look at the source code. I don't know
> anything about Python-Evolution, but if you're prepared to do a bit of
> digging, you can probably find what you want here:
> 
> http://git.gnome.org/browse/gnome-python-desktop/tree/evolution/
> 
Yes, thank you, I couldn't even find that.

> (You probably have a copy of the same content on your own hard disk
> somewhere, too.)
> 
> Once you figure out what you wanted, do consider sending a patch to
> the maintainer(s), improving the docstrings and/or external
> documentation, so the next person has an easier task. :)
> 
Actually I'm not sure if it's down to the docstrings because the help
available from Python itself stops (not unreasonably) at the interface
to the C library code.  What I was after (and you have told me where
it is) was the functions/methods available from the C library.

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


Re: unittest. customizing tstloaders / discover()

2011-12-12 Thread Nathan Rice
Nose is absolutely the way to go for your testing needs.  You can put
"__test__ = False" in modules or classes to stop test collection.

On Mon, Dec 12, 2011 at 5:44 AM, Thomas Bach  wrote:
> Gelonida N  writes:
>
>> Do I loose anything if using nose. or example can all unit tests / doc
>> tests still be run from nose?
>
> AFAIK you don't loose anything by using nose – the unittests should all
> be found and doctests can be run via `--with-doctest', I never used
> doctests though.
>
> regards
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Jussi Piitulainen
Terry Reedy writes:
> On 12/12/2011 5:59 AM, Jussi Piitulainen wrote:
> 
> > Past experience in mathematics newsgroups tells me
> > that some mathematicians do not accept the existence of any remainder
> > operator at all.
> 
> Even though they carry hour/minute/second remindering devices on their
> bodies and put year/month/day remaindering devices on their wall?
> 'Twould be strange indeed!

They recognize modular arithmetic but for some reason insist that
there is no such _binary operation_. But as I said, I don't understand
their concern. (Except the related concern about some programming
languages, not Python, where the remainder does not behave well with
respect to division.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco

> > I personally quite like them, but I would like them to be more general.
>
> It already is. The *target can be anywhere in the sequence.

Im not sure if this is a genuine understanding, or trollish
obtuseness.

Yes, the target can be anywhere in the sequence. And yes, the
resulting list can contain objects of any type, so its very flexible
in that regard too.

But to relate it to the topic of this thread: no, the syntax does not
allow one to select the type of the resulting sequence. It always
constructs a list.

Yes, we can cast the list to be whatever we want on the next line, but
the question is whether this language design can be improved upon. The
choice of a list feels arbitrary, adding another line to cast it to
something else would be even more verbose, and whats more, there would
be serious performance implications if one should seek to apply this
pattern to a deque/linkedlist; it would make taking off the head/tail
of the list from a constant to a linear operation.

That is:

>>> head, deque(tail) = somedeque

Is better in every way I can think of (readability, consistence,
performance) than:

>>> head, *tail = somedeque
>>> tail = deque(tail)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
> They recognize modular arithmetic but for some reason insist that
> there is no such _binary operation_. But as I said, I don't understand
> their concern. (Except the related concern about some programming
> languages, not Python, where the remainder does not behave well with
> respect to division.)

They might not be willing to define it, but as soon as we programmers
do, well, we did.

Having studied the contemporary philosophy of mathematics, their
concern is probably that in their minds, mathematics is whatever some
dead guy said it was, and they dont know of any dead guy ever talking
about a modulus operation, so therefore it 'does not exist'.

Whatever you want to call the concept we are talking about, or whether
you care to talk about it at all, it is most certainly a binary
operation, since there are two arguments involved. There is no way
around that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread gene heskett
On Monday, December 12, 2011 12:44:27 PM Chris Angelico did opine:

> On Tue, Dec 13, 2011 at 2:55 AM, Nick Dokos  
wrote:
> > Terry Reedy  wrote:
> >> calculations are helped by the fact that (a+b) % c == a%c + b%c, so
> > 
> > As long as we understand that == here does not mean "equal", only
> > "congruent modulo c", e.g try a = 13, b = 12, c = 7.
> 
> This is the basis of the grade-school "casting out nines" method of
> checking arithmetic. Set c=9 and you can calculate N%c fairly readily
> (digit sum - I'm assuming here that the arithmetic is being done in
> decimal); the sum of the remainders should equal the remainder of the
> sum, but there's the inherent assumption that if the remainders sum to
> something greater than nine, you digit-sum it to get the true
> remainder.
> 
> (Technically the sum of the digits of a base-10 number is not the same
> as that number mod 9, but if you accept that 0 == 9, it works fine.)
> 
> ChrisA

And that is precisely the reason I have failed to understand why the 1-10 
decimal system seems to have hung on for several hundred years when it is 
clearly broken.

Cheers, Gene
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
My web page: 
Grub first, then ethics.
-- Bertolt Brecht
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Nick Dokos
Jussi Piitulainen  wrote:

> Terry Reedy writes:
> > On 12/12/2011 5:59 AM, Jussi Piitulainen wrote:
> > 
> > > Past experience in mathematics newsgroups tells me
> > > that some mathematicians do not accept the existence of any remainder
> > > operator at all.
> > 
> > Even though they carry hour/minute/second remindering devices on their
> > bodies and put year/month/day remaindering devices on their wall?
> > 'Twould be strange indeed!
> 
> They recognize modular arithmetic but for some reason insist that
> there is no such _binary operation_. But as I said, I don't understand
> their concern. (Except the related concern about some programming
> languages, not Python, where the remainder does not behave well with
> respect to division.)

They are probably arguing that it's uniquely defined only on ZxN and
that there are different conventions to extend it to ZxZ (the programming
languages problem that you allude to above - although I don't know what you
mean by "does not behave well wrt division"). See

 http://en.wikipedia.org/wiki/Remainder

If you choose one convention and stick to it, it becomes a well-defined
binary operation. C99 goes one way, python goes a different way (and
mathematics textbooks generally go a third way) and they are all happy,
as long as they don't try to talk to each other (e.g., porting C99
programs to python unthinkingly leads to trouble - duh). It was
implementation dependent in old C (whatever the hardware would give
you), which predictably - with 20-20 hindsight - turned out to be a Very
Bad Idea.

Nick

PS  Z = integers, N = non-negative integers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Dave Angel

On 12/12/2011 12:46 PM, gene heskett wrote:

On Monday, December 12, 2011 12:44:27 PM Chris Angelico did opine:


This is the basis of the grade-school "casting out nines" method of
checking arithmetic. Set c=9 and you can calculate N%c fairly readily
(digit sum - I'm assuming here that the arithmetic is being done in
decimal); the sum of the remainders should equal the remainder of the
sum, but there's the inherent assumption that if the remainders sum to
something greater than nine, you digit-sum it to get the true
remainder.

(Technically the sum of the digits of a base-10 number is not the same
as that number mod 9, but if you accept that 0 == 9, it works fine.)

ChrisA

And that is precisely the reason I have failed to understand why the 1-10
decimal system seems to have hung on for several hundred years when it is
clearly broken.

I assume this was facetious, but in case not, I'd point out that any 
other number base will have similar modulo characteristics, except for 
base 2, where all numbers are congruent modulo 1, so it doesn't do much 
for checking values.


For example, if you were using a number system of base 8, you could do 
"casting out sevens" by adding the digits together.


--

DaveA

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 5:21 AM, Eelco  wrote:
> You cannot; only constructors modelling a sequence or a dict, and
> only
> in that order. Is that rule clear enough?

The dict constructor can receive either a sequence or a mapping, so if
I write this:

def func(a, b, dict(c)):

what will I get?  Probably I would want the equivalent of:

def func(a, b, **c):

but you seem to be saying that I would actually get the equivalent of this:

def func(a, b, *c):
c = dict(c)

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Jussi Piitulainen
Eelco writes:

> > They recognize modular arithmetic but for some reason insist that
> > there is no such _binary operation_. But as I said, I don't understand
> > their concern. (Except the related concern about some programming
> > languages, not Python, where the remainder does not behave well with
> > respect to division.)
> 
> They might not be willing to define it, but as soon as we programmers
> do, well, we did.
> 
> Having studied the contemporary philosophy of mathematics, their
> concern is probably that in their minds, mathematics is whatever some
> dead guy said it was, and they dont know of any dead guy ever talking
> about a modulus operation, so therefore it 'does not exist'.
> 
> Whatever you want to call the concept we are talking about, or whether
> you care to talk about it at all, it is most certainly a binary
> operation, since there are two arguments involved. There is no way
> around that.

Yes, I think you nailed it.

But I guess I'll still be confused the next time I meet one of them.
Happens to me. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Nick Dokos
gene heskett  wrote:

> On Monday, December 12, 2011 12:44:27 PM Chris Angelico did opine:
> 
> > On Tue, Dec 13, 2011 at 2:55 AM, Nick Dokos  
> wrote:
> > > Terry Reedy  wrote:
> > >> calculations are helped by the fact that (a+b) % c == a%c + b%c, so
> > > 
> > > As long as we understand that == here does not mean "equal", only
> > > "congruent modulo c", e.g try a = 13, b = 12, c = 7.
> > 
> > This is the basis of the grade-school "casting out nines" method of
> > checking arithmetic. Set c=9 and you can calculate N%c fairly readily
> > (digit sum - I'm assuming here that the arithmetic is being done in
> > decimal); the sum of the remainders should equal the remainder of the
> > sum, but there's the inherent assumption that if the remainders sum to
> > something greater than nine, you digit-sum it to get the true
> > remainder.
> > 
> > (Technically the sum of the digits of a base-10 number is not the same
> > as that number mod 9, but if you accept that 0 == 9, it works fine.)
> > 
> > ChrisA
> 
> And that is precisely the reason I have failed to understand why the 1-10 

It's not clear from the above what you mean by "that is presicely the reason":
what is "that"? 

> decimal system seems to have hung on for several hundred years when it is 
> clearly broken.
> 

"broken" how?

Thanks,
Nick



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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
On Dec 12, 7:09 pm, Ian Kelly  wrote:
> On Mon, Dec 12, 2011 at 5:21 AM, Eelco  wrote:
> > You cannot; only constructors modelling a sequence or a dict, and
> > only
> > in that order. Is that rule clear enough?
>
> The dict constructor can receive either a sequence or a mapping, so if
> I write this:
>
>         def func(a, b, dict(c)):
>
> what will I get?  Probably I would want the equivalent of:
>
>         def func(a, b, **c):
>
> but you seem to be saying that I would actually get the equivalent of this:
>
>         def func(a, b, *c):
>             c = dict(c)
>
> Cheers,
> Ian

Im not sure if I was clear on that, but I dont care what the
constructors accept; I meant to overload on the concept the underlying
type models. Dicts model a mapping, lists/tuples model a sequence. MI
deriving from both these models is illegal anyway, so one can
unambigiously overload on that trait.

The syntax only superficially resembles 'call the dict constructor
with the object passed into kwargs'. What its supposed to mean is
exactly the same as **kwargs, but with added flexibility.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 11:17 AM, Eelco  wrote:
> Im not sure if I was clear on that, but I dont care what the
> constructors accept; I meant to overload on the concept the underlying
> type models. Dicts model a mapping, lists/tuples model a sequence. MI
> deriving from both these models is illegal anyway, so one can
> unambigiously overload on that trait.

False.

>>> from collections import *
>>> class Foo(Sequence, Mapping):
... def __init__(self, items):
... self._items = items
... def __getitem__(self, item):
... return self._items[item]
... def __len__(self):
... return len(self._items)
...
>>> foo1 = Foo(range(5, 10))
>>> foo2 = Foo({'one': 1, 'two': 2})
>>> foo1[3]
8
>>> foo2['one']
1

Or are you saying that only classes specifically derived from list,
tuple, or dict should be considered, and custom containers that are
not derived from any of those but implement the correct protocols
should be excluded?  If so, that sounds less than ideal.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
> False.

I stand corrected.

> Or are you saying that only classes specifically derived from list,
> tuple, or dict should be considered, and custom containers that are
> not derived from any of those but implement the correct protocols
> should be excluded?  If so, that sounds less than ideal.

That might be a desirable constraint from an implementational/
performance aspect anyway, but I agree, less than ideal.

Either way, its not hard to add some detail to the semantics to allow
all this. Even this function definition:

def func(Foo(args), Foo(kwargs))

...could even be defined unambigiously by overloading first on base
type, and if that does not uniquely determine the args and kwargs,
fall back on positionality, so that:

def func(Foo(args), dict(kwargs))
def func(list(args), Foo(kwargs))

would be uniquely defined as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
To get back on topic a little bit, lets get back to the syntax of all
this: I think we all agree that recycling the function call syntax is
less than ideal, since while it works in special contexts like a
function signature, its symmetric counterpart inside a function call
already has the meaning of a function call.

In general, we face the problem of specifying metadata about a
variable, or a limited form of type constraint.

What we want is similar to function annotations in python 3; in line
with that, we could have more general variable annotations. With an
important conceptual distinction; function annotations are meaningless
to python, but the annotations I have in mind should modify semantics
directly. However, its still conceptually close enough that we might
want to use the colon syntax here too. To distinguish it from function
annotations, we could use a double colon (double colon is an
annotation with non-void semantics; quite a simple rule); or to
maintain an historic link with the existing packing/unpacking syntax,
we could look at an augmented form of the asteriks notation.

For instance:

def func(list*args, dict*kwargs) <- list-of-args, dict-of-kwargs
def func(args::list, kwargs::dict) <- I like the readability of this
one even better; args-list and kwargs-dict

And:

head, deque*tail = somedeque
head, tail::deque = somedeque

Or some variants thereof
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
On Dec 12, 8:05 pm, Eelco  wrote:
> To get back on topic a little bit, lets get back to the syntax of all
> this: I think we all agree that recycling the function call syntax is
> less than ideal, since while it works in special contexts like a
> function signature, its symmetric counterpart inside a function call
> already has the meaning of a function call.
>
> In general, we face the problem of specifying metadata about a
> variable, or a limited form of type constraint.
>
> What we want is similar to function annotations in python 3; in line
> with that, we could have more general variable annotations. With an
> important conceptual distinction; function annotations are meaningless
> to python, but the annotations I have in mind should modify semantics
> directly. However, its still conceptually close enough that we might
> want to use the colon syntax here too. To distinguish it from function
> annotations, we could use a double colon (double colon is an
> annotation with non-void semantics; quite a simple rule); or to
> maintain an historic link with the existing packing/unpacking syntax,
> we could look at an augmented form of the asteriks notation.
>
> For instance:
>
> def func(list*args, dict*kwargs) <- list-of-args, dict-of-kwargs
> def func(args::list, kwargs::dict) <- I like the readability of this
> one even better; args-list and kwargs-dict
>
> And:
>
> head, deque*tail = somedeque
> head, tail::deque = somedeque
>
> Or some variants thereof

As for calling functions; calling a function with the content of a
collection type rather than the collection as an object itself is a
rather weird special case operation I suppose, but we can cover it
with the same syntax:

def func(args::tuple, kwargs::dict):
funccall(args::, kwargs::) <- void type constraint means
unpacking, for symmetry with args/kwargs aggregation
funccall(::args, ::kwargs) <- I like this better, to emphasize it
being 'the other side' of the same coin, and quite close to ** syntax

Sequence and Mapping unpacking dont need their own symbols, if things
are done like this, since in the function declaration the meaning is
clear from the type of the annotations used, plus their position, and
in the call the meaning is clear from the type of the object
undergoing to unpacking operation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: executable builder

2011-12-12 Thread J A
I am having some issues compiling an exe myself but most of that stems from the 
version of python I am using.  That being said, try using GUI2EXE 
http://code.google.com/p/gui2exe this program makes the setup file go a lot 
easier, also it will tie in a few different tools like py2exe which is what I 
have been working with, also it does include py2app (the mac version).  If you 
decide to go this route please pay careful attention to 
http://py2exe.org/index.cgi/Tutorial#Step52 if using python26, this bit of 
instruction could have saved me hours of banging my head on my desk.

> On Thursday, July 01, 2010 3:16 AM King wrote:

> Hi,
> 
> I am trying to build python a cross platform python executable builder
> to deploy python app. I tried various tools such as py2exe,
> pyinstaller, cx_freeze but some how they are not upto the mark except
> py2exe. Unfortunately py2exe is working only on windows based systems.
> 
> The task is divide into 3 steps:
> 1. Collect all the modules(.pyo, .pyd, .dll, etc) required for your
> project.
> 2. set up temporary environment for python
> 3. run main.py using :python.exe main.py
> 
> Initially I will not be creating an executable using main.py. I would be
> using shell scripting to execute the main.py.
> 
> Q1. Which is most efficient way to fine all the modules required by
> your "main.py".
> Q2. For example, I have copied all the modules in "d:\project\lib\*.*"
> python.exe, python.dll, ms*.dll, main.py are copied to "d:
> \project".
> Before executing "python.exe main.py", I have to set up an
> environment var and point it to "d:\project\lib", so
> that python.exe can find the path for searching/loading
> modules. How do I do that?
> Q3. How do you convert your "main.py" into an executable?
> 
> Prashant



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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread OKB (not okblacke)
Steven D'Aprano wrote:

> And you can blame C for the use of % instead of mod or modulo.

Anytime you can blame C for something, you can also blame a bunch 
of other languages for foolishly perpetuating the inanities of C.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Documentation for python-evolution - where?

2011-12-12 Thread Chris Angelico
On Tue, Dec 13, 2011 at 3:40 AM,   wrote:
> Actually I'm not sure if it's down to the docstrings because the help
> available from Python itself stops (not unreasonably) at the interface
> to the C library code.  What I was after (and you have told me where
> it is) was the functions/methods available from the C library.

Ah, yes, I know that problem! Let's see, how many high level
languages/libraries have I used that have simply exposed a lower-level
API without documenting it? REXX/REXXUtil and SysSetObjectData was the
first. More recently, Pike and the GTK/GTK2 modules. In between, oh so
many others.

Depending on how much is exposed and how transparent the local layer,
it may still be worth writing up some better documentation. Or if not,
it may be of value for the docs to incorporate a link to some
"upstream documentation", which would accomplish the same thing. (It's
a shot at immortality - get your name in a big project's revision
history!)

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


Re: automate commands to an .exe console program through python

2011-12-12 Thread Chris Angelico
On Tue, Dec 13, 2011 at 3:41 AM, Juan Perez  wrote:
> I need to automate a .exe console program in windows, and send key
> characters like 'a', 'M' ...
> I had this running in an autoIT script which with only activating cmd
> window, and with the "send" parameter I had all already done. But I'm having
> a lot of problems with python, I've tried with process.call, communicate(),
> os.popen ... but no results. I can't comunicate with the program and even i
> can't maintain it opened more than  a few seconds. If I open a program like
> notepad.exe it remains opened but when I try to comunicate with the stdin
> pipe just don't write anything to the program.

GUI programs such as Notepad usually don't read from STDIN, which is
where text goes if you write to a pipe. You may have to check out how,
exactly, the program accepts commands; your autoIT script is probably
sending keystrokes using the Wndows GUI, so it works as long as the
program has focus.

Ideally, look into whether the program has an actual automation mode -
and if it doesn't have one, ask the programmer to expose his code
directly to a Python script. Hey, it's worth a shot! :)

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


Re: Overriding a global

2011-12-12 Thread Steven D'Aprano
On Mon, 12 Dec 2011 12:13:33 +0100, Jean-Michel Pichavant wrote:

> Using the same name for 2 different objects is a bad idea in general.

We have namespaces precisely so you don't need to care about making names 
globally unique.


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


Re: Overriding a global

2011-12-12 Thread Dave Angel

On 12/12/2011 04:28 PM, Steven D'Aprano wrote:

On Mon, 12 Dec 2011 12:13:33 +0100, Jean-Michel Pichavant wrote:


Using the same name for 2 different objects is a bad idea in general.

We have namespaces precisely so you don't need to care about making names
globally unique.


True, but in this code, the function is trying to both use the global 
value, but also a local that deliberately has the same name, but a 
different meaning and "value".  The CPython compiler doesn't make this 
easy, and I think the globals() technique is unnecessarily obscure, as 
is the default-argument trick.


If a function knows of the presence of a global, it's not asking too 
much for it to not re-use the same name in local scope.


Since it seems to be in vogue to propose language changes, how about a 
new place for 'as' ?

def myfunc():
 global logger as g_logger
 logger = g_logger.debug('stuff').getChild('function')

--

DaveA

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


Re: Overriding a global

2011-12-12 Thread Joshua Landau
Wouldn't this be nicer, though?:

def getChildLogger(id):
return logger.getChild(id)

def someFunc():
logger = getChildLogger("someFunc")


-- UNTESTED --

No messing around with globals this way, and it's more extendable. And
'globals()["logger"].getChild("someFunc")' reads like a brick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Terry Reedy

On 12/12/2011 12:12 PM, Eelco wrote:


Im not sure if this is a genuine understanding, or trollish
obtuseness.


If you are referring to what I write, it is based on genuine 
understanding of Python.



Yes, the target can be anywhere in the sequence. And yes, the
resulting list can contain objects of any type, so its very flexible
in that regard too.

But to relate it to the topic of this thread: no, the syntax does not
allow one to select the type of the resulting sequence. It always
constructs a list.


One use case of *target is to ignore the stuff collected in the target 
because one only wants a few end values from the iterable. Another is to 
pull stuff out because one wants to iterate through the rest. For both 
uses, a list is as good as anything.



Yes, we can cast the list to be whatever we want on the next line,


Convert. For the very few cases one wants to do this, it is quite adequate.

> but the question is whether this language design can be improved upon.

Not easily.


The choice of a list feels arbitrary,


On the contrary, a list is precisely what is needed to collect an 
indefinite number of leftovers.


> adding another line to cast it to

something else would be even more verbose, and whats more, there would
be serious performance implications if one should seek to apply this
pattern to a deque/linkedlist; it would make taking off the head/tail
of the list from a constant to a linear operation.


For a linked list, no *target and no copying is needed:

head, tail = llist


head, deque(tail) = somedeque


Is better in every way I can think of (readability, consistence,
performance) than:



head, *tail = somedeque
tail = deque(tail)


But your suggestion is much worse in each way than

head = somedeque.popleft()

To repeat, there is no reason to copy even once. If one does not want to 
mutate the deque, then one mutates an iterator view of the deque.


--
Terry Jan Reedy

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


curses (or something) for windows

2011-12-12 Thread Eric
Is there something similar to curses available for the Windows version
of Python (2.7, community edition)?  Preferably something built-in.
In general, I'm looking to do gui-ish things from within the command
window.

Also, in particular, is there a way to get the console size (rows,
cols).  I've seen how to do it in unix land but not for windows.

TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding a global

2011-12-12 Thread Ben Finney
Dave Angel  writes:

> True, but in this code, the function is trying to both use the global
> value, but also a local that deliberately has the same name, but a
> different meaning and "value". The CPython compiler doesn't make this
> easy, and I think the globals() technique is unnecessarily obscure, as
> is the default-argument trick.

I disagree. The language makes it difficult, and it *should* be
difficult to do what you describe.

The tricks to achieve it are obscure and ugly, which is a good thing
IMO: they're a code smell that the design of the code needs changing.

Or, in brief: they're not unnecessarily obscure, they're as obscure as
they need to be.

> If a function knows of the presence of a global, it's not asking too
> much for it to not re-use the same name in local scope.

Yes. 

-- 
 \ “Airports are ugly. Some are very ugly. Some attain a degree of |
  `\ugliness that can only be the result of a special effort.” |
_o__) —Douglas Adams, _The Long Dark Tea-Time Of The Soul_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding a global

2011-12-12 Thread Joshua Landau
>
> > If a function knows of the presence of a global, it's not asking too
> > much for it to not re-use the same name in local scope.
>
> Yes.


It's just a function wanting to act as-if it were in a different
environment than its default. By that same reasoning you could state that
"If a function knows of the presence of a built-in, it's not asking
too much for it to not re-use the same name in local scope." Yet if
rebinding "id" is such a crime, why is it so oft done? Rebinding logger
locally in a function is really no different to a subclass rebinding a
variable from its main class using that class' value. *The only difference
is that, in that case, you have an alternate binding to the original value.*
*
*
>>> class A():
... val = 1
...
>>> class B(A):
... val = str(val) # Obviously, this doesn't work
...

NameError: name 'val' is not defined
>>> class B(A):
... val = str(A.val) # But it's OK as we can just do this ^^
...
>>> B().val
'1'
>>>

The only reason it's not minded with classes is because there's a good way
to do it.

I get that my analogy doesn't use globals, but the idea of extending a
more-global attribute locally is shared between the concepts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: curses (or something) for windows

2011-12-12 Thread alex23
On Dec 13, 7:15 am, Eric  wrote:
> Is there something similar to curses available for the Windows version
> of Python (2.7, community edition)?  Preferably something built-in.
> In general, I'm looking to do gui-ish things from within the command
> window.
>
> Also, in particular, is there a way to get the console size (rows,
> cols).  I've seen how to do it in unix land but not for windows.
>
> TIA,
> eric

Check out http://www.lfd.uci.edu/~gohlke/pythonlibs/

It's a fantastic resource, Win32 & 64 versions of a lot of packages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic variable creation from string

2011-12-12 Thread alex23
On Dec 12, 10:49 pm, 8 Dihedral 
wrote:
> This is the way to write an assembler or
> to roll out a script language to be included in an app
> by users.

This is a garbage comment that has absolutely nothing to do with the
topic at hand _at all_.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread alex23
On Dec 12, 10:21 pm, Eelco  wrote:
> >  Modulo is hardly an obscure operation. "What's the remainder...?" is a
> >  simple question that people learn about in primary school.
>
> So is 'how much wood would a woodchucker chuck if a woodchucker could
> chuck wood?'. But how often does that concept turn up in your code?

That comment right there? That's the moment every serious coder
stopped paying attention to a single word you say.

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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Eelco
> > Im not sure if this is a genuine understanding, or trollish
> > obtuseness.
>
> If you are referring to what I write, it is based on genuine
> understanding of Python.

This is getting 'interesting'. In a way. I meant to write
'misunderstanding', as I think the context made quite clear. So again
this adds another layer of doubt as to whether you are being obtuse
for its own sake, or if there is yet another layer of misunderstanding
stacked on top of the others. Either way, lets continue with the
benefit of the doubt.

> One use case of *target is to ignore the stuff collected in the target
> because one only wants a few end values from the iterable. Another is to
> pull stuff out because one wants to iterate through the rest. For both
> uses, a list is as good as anything.

So what is the point of having different sequence types, if a list can
do anything? I would argue that the different performance
characteristics and differences in semantics give each sequence type
ample reason for existence.

> Convert. For the very few cases one wants to do this, it is quite adequate.

Or so you opine. As you may recall, the original idea was motivated by
args/kwargs syntactic clarity and flexibility; I merely shifted focus
to this use case of collection unpacking since it is somewhat simpler
and easier to discuss. Keep that in mind, should you seek to build a
case for that assertion in the future.

>  > but the question is whether this language design can be improved upon.
>
> Not easily.

Again, so you opine. Care to give a refutation of my proposed double
colon syntax? Ignoring for a moment whether or not it is useful; does
it clash with anything? I havnt been able to think of anything in the
past few hours, but im not taking that to mean much; there are
probably some subtleties I am overlooking. I think it dos not clash
with slicing syntax for instance, but im not sure.

> For a linked list, no *target and no copying is needed:
>
> head, tail = llist

I have no idea what this means.

>  head, deque(tail) = somedeque
>
> > Is better in every way I can think of (readability, consistence,
> > performance) than:
>  head, *tail = somedeque
>  tail = deque(tail)
>
> But your suggestion is much worse in each way than
>
> head = somedeque.popleft()

No its not. First of all, its not semantically equivalent; popleft
mutates a collection type, and collection unpacking does not; it
creates a set of disjoint views of the collection's data. Whether its
worse in terms of readability is debatable, but in terms of the other
two stated metrics, your claim of it being any kind of worse is
objectively false.

Furthermore, this brings us back again to the point I raised several
times before. Yes, obviously you can already DO these things, but NOT
within the same uniform collection unpacking syntactic construct.
Again, you have failed to point out what is wrong with supplying a
type constrain to python and let it do the right thing based on that;
to reiterate:

head, tail::deque = deque

No need to mutate anything; python can create the view of the
linkedlist internally. A single unambigious syntax, and single
unambigious semantics, for all sequence types. Whats not to like?

If you dont like the extra characters you have to type; there is of
course such a thing as defaults. You can choose:
head, tail:: = deque; if the type constraint is omitted, we could make
tail a list by default, or my preferred solution, infer it from the
right hand side type. In case of the former, all you had to do was
type :: instead of *, and your python universe would otherwise be
completely unchanged. If thats 'not easily', I dont know what is.

> To repeat, there is no reason to copy even once. If one does not want to
> mutate the deque, then one mutates an iterator view of the deque.

And arrive at yet another construction to do the same thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread alex23
On Dec 13, 3:12 am, Eelco  wrote:
> But to relate it to the topic of this thread: no, the syntax does not
> allow one to select the type of the resulting sequence. It always
> constructs a list.

So by this argument, _every_ function that returns a list should take
an optional argument to specify an alternative form of sequence.

What, exactly, is so onerous about coercing your list to _whatever_
type you want? You know, like everybody else has been.

What does this _gain_ you other than one less line of code?


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 11:51 AM, Eelco  wrote:
> Either way, its not hard to add some detail to the semantics to allow
> all this. Even this function definition:
>
> def func(Foo(args), Foo(kwargs))
>
> ...could even be defined unambigiously by overloading first on base
> type, and if that does not uniquely determine the args and kwargs,
> fall back on positionality, so that:
>
> def func(Foo(args), dict(kwargs))
> def func(list(args), Foo(kwargs))
>
> would be uniquely defined as well.

That solves some of the problems, but if I just have:

def func(SequenceOrMappingType(args)):

That's going to unpack positionally.  If I want it to unpack keywords
instead, how would I change the definition to indicate that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: curses (or something) for windows

2011-12-12 Thread Eric
On Dec 12, 5:47 pm, alex23  wrote:
> On Dec 13, 7:15 am, Eric  wrote:
>
> > Is there something similar to curses available for the Windows version
> > of Python (2.7, community edition)?  Preferably something built-in.
> > In general, I'm looking to do gui-ish things from within the command
> > window.
>
> > Also, in particular, is there a way to get the console size (rows,
> > cols).  I've seen how to do it in unix land but not for windows.
>
> > TIA,
> > eric
>
> Check outhttp://www.lfd.uci.edu/~gohlke/pythonlibs/
>
> It's a fantastic resource, Win32 & 64 versions of a lot of packages.

Wowee that's a lot of stuff.  Thanks for the tip.

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


Re: I love the decorator in Python!!!

2011-12-12 Thread alex23
On Dec 13, 2:27 am, Robert Kern  wrote:
> On 12/12/11 3:36 AM, alex23 wrote:
>
> > On Dec 9, 8:08 pm, Robert Kern  wrote:
> >> On 12/9/11 5:02 AM, alex23 wrote:
> >>> The 3rd party 'decorator' module takes care of issues like docstrings
> >>> &    function signatures. I'd really like to see some of that
> >>> functionality in the stdlib though.
>
> >> Much of it is:
>
> >>    http://docs.python.org/library/functools#functools.update_wrapper
>
> > Ah, cheers :) Is that a recent addition? The lack of note makes it
> > seem like it was there from the beginning?
>
> The module was added in Python 2.5 as noted at the top of the page.

I had thought you meant it now included function signature handling,
as that was the context at the time. No biggie.
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple legend code no longer works after upgrade to Ubuntu 11.10

2011-12-12 Thread C Barrington-Leigh
rom pylab import *
plot([0,0],[1,1],label='Ubuntu 11.10')
Before I upgraded to 2.7.2+ / 4 OCt 2011, the following code added a
comment line with a legend.
Now, the same code makes the legend appear "off-screen", ie way
outside the axes limits.

Can anyone help? And/or is there a new way to add a title and footer
to the legend?

Thanks!


lh=legend(fancybox=True,shadow=False)
lh.get_frame().set_alpha(0.5)

from matplotlib.offsetbox import TextArea, VPacker
fontsize=lh.get_texts()[0].get_fontsize()
legendcomment=TextArea('extra comments here',
textprops=dict(size=fontsize))
show()
# Looks fine here
lh._legend_box = VPacker(pad=5,
 sep=0,
 children=[lh._legend_box,legendcomment],
 align="left")
lh._legend_box.set_figure(gcf())
draw()
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple legend code no longer works after upgrade to Ubuntu 11.10

2011-12-12 Thread C Barrington-Leigh

"""
Before I upgraded to 2.7.2+ / 4 OCt 2011, the following code added a
comment line to an axis legend using matplotlib / pylab.
Now, the same code makes the legend appear "off-screen", ie way
outside the axes limits.

Can anyone help? And/or is there a new way to add a title and footer
to the legend?

Thanks!
"""

from pylab import *
plot([0,0],[1,1],label='Ubuntu 11.10')
lh=legend(fancybox=True,shadow=False)
lh.get_frame().set_alpha(0.5)

from matplotlib.offsetbox import TextArea, VPacker
fontsize=lh.get_texts()[0].get_fontsize()
legendcomment=TextArea('extra comments here',
textprops=dict(size=fontsize))
show()
# Looks fine here
lh._legend_box = VPacker(pad=5,
 sep=0,
 children=[lh._legend_box,legendcomment],
 align="left")
lh._legend_box.set_figure(gcf())
draw()


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Steven D'Aprano
On Mon, 12 Dec 2011 16:58:33 -0500, Terry Reedy wrote:

> On 12/12/2011 12:12 PM, Eelco wrote:

>> Yes, we can cast the list to be whatever we want on the next line,
> 
> Convert. For the very few cases one wants to do this, it is quite
> adequate.

+1

with the small proviso that there's not much you can usefully do with a 
dict. If you convert to an ordered dict, the initial order is lost by the 
time you see it; if you want to allow duplicates, duplicates are likewise 
lost (or in a function call, an exception is raised).

In Python 4000, I'd like to see some way to pass arbitrary parameters to 
functions, including duplicates. That is, emulating the richness of 
command line argument handling in functions.

In Python 3.x, I'd like to see OrderedDict become a built-in, and then 
**kwargs can collect named arguments in an ordered dict without losing 
the order.



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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 4:40 PM, Eelco  wrote:
>> For a linked list, no *target and no copying is needed:
>>
>> head, tail = llist
>
> I have no idea what this means.

Each node of a linked list consists of a data member and a "next"
member, that holds the next node in the list.  The natural container
for this and the way it is usually implemented in Python is a
2-element tuple.  For example:

llist = ('one', ('two', ('three', ('four', None

would be a linked list as typically constructed in Python, and it can
be used in pretty much the same way that lists are used in Lisp.  The
result of the operation:

head, tail = llist

is:

head = 'one'
tail = ('two', ('three', ('four', None)))

and as Terry pointed out, no copying is required to do this.  I
believe deque is also implemented as a doubly-linked list, which is
probably why you keep referring to it as such, but that is an
implementation detail.  When you say "linked list" in relation to
Python, the preceding is what comes to mind.

>>  head, deque(tail) = somedeque
>>
>> > Is better in every way I can think of (readability, consistence,
>> > performance) than:
>>  head, *tail = somedeque
>>  tail = deque(tail)
>>
>> But your suggestion is much worse in each way than
>>
>> head = somedeque.popleft()
>
> No its not. First of all, its not semantically equivalent; popleft
> mutates a collection type, and collection unpacking does not; it
> creates a set of disjoint views of the collection's data. Whether its
> worse in terms of readability is debatable, but in terms of the other
> two stated metrics, your claim of it being any kind of worse is
> objectively false.

I definitely disagree on readability.  Skimming this thread as I have
been, it took me a while to get that your proposed syntax would create
a second deque sharing internal state with the original, rather than
creating a simple copy of the deque, which is what it looks like it
should do.

Incidentally, while that change is not really central to your syntax
proposal, I think it would be very messy.  For example, how do you
propose keeping the length elements in sync?  Inserting an item in one
may or may not affect the length of the other.  If I append an item to
the end of one deque, should the other automatically be extended as
well?  What if the tail node of the second deque occurs after the tail
node of the deque being appended?  Does the appended element then get
inserted into the middle of the second deque (I think it would have to
be)?  If I insert an element into the longer (second) deque that just
happens to be immediately after the tail of the shorter deque, does
*that* cause the shorter deque to be automatically extended?  And
likewise for operations at the head of the deque.

None of these questions have obvious answers as to the "right" way to
it, and for that reason I think this is probably best left to the user
to implement a custom deque view class with whatever semantics they
prefer.

> Furthermore, this brings us back again to the point I raised several
> times before. Yes, obviously you can already DO these things, but NOT
> within the same uniform collection unpacking syntactic construct.
> Again, you have failed to point out what is wrong with supplying a
> type constrain to python and let it do the right thing based on that;
> to reiterate:
>
> head, tail::deque = deque

Python users generally follow the rule "explicit is better than
implicit".  Setting a general constraint and letting the language "do
the right thing" is a kind of black magic that feels off because it
tends to break that rule.  But that's not to say that black magic
never wins -- just look at super() and the MRO.

> If you dont like the extra characters you have to type; there is of
> course such a thing as defaults. You can choose:
> head, tail:: = deque; if the type constraint is omitted, we could make
> tail a list by default, or my preferred solution, infer it from the
> right hand side type.

I prefer the former.  If it always creates a list by default, then the
programmer reading this code three years later knows exactly what the
type of tail is.  If it instead infers it from the sequence being
unpacked, then the programmer is forced to infer it as well, and it
won't necessarily be obvious or even consistent.

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


Re: Dynamic variable creation from string

2011-12-12 Thread Steven D'Aprano
On Mon, 12 Dec 2011 15:45:06 -0800, alex23 wrote:

> On Dec 12, 10:49 pm, 8 Dihedral 
> wrote:
>> This is the way to write an assembler or to roll out a script language
>> to be included in an app by users.
> 
> This is a garbage comment that has absolutely nothing to do with the
> topic at hand _at all_.

Please stop responding to the bot.



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


Re: Overriding a global

2011-12-12 Thread Dave Angel

On 12/12/2011 06:48 PM, Joshua Landau wrote:

If a function knows of the presence of a global, it's not asking too
much for it to not re-use the same name in local scope.

Yes.


It's just a function wanting to act as-if it were in a different
environment than its default. By that same reasoning you could state that
"If a function knows of the presence of a built-in, it's not asking
too much for it to not re-use the same name in local scope."

It's entirely different.  It's only the same if the function actually 
tries to call the built-in, then also wants a local variable with a 
different purpose.  Think a little about what I mean that the function 
"knows of the presence."  I did not say the programmer knows of the 
presence.

--

DaveA

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


Re: Overriding a global

2011-12-12 Thread Steven D'Aprano
On Tue, 13 Dec 2011 09:27:09 +1100, Ben Finney wrote:

> Dave Angel  writes:
> 
>> True, but in this code, the function is trying to both use the global
>> value, but also a local that deliberately has the same name, but a
>> different meaning and "value". The CPython compiler doesn't make this
>> easy, and I think the globals() technique is unnecessarily obscure, as
>> is the default-argument trick.
> 
> I disagree. The language makes it difficult, and it *should* be
> difficult to do what you describe.
> 
> The tricks to achieve it are obscure and ugly, which is a good thing
> IMO: they're a code smell that the design of the code needs changing.

Devil's Advocate: perhaps not. Think of local and global names as 
analogous to instance and class attributes. There are good use cases for 
making something a class attribute, while allowing instances to override 
that name with an instance attribute. I see a reasonable case for saying 
"use this global, unless a local overrides it".

Similarly, globals override built-ins with the same name; while 
monkeypatching needs to be used with care, it is a legitimate technique.

To a human reader, the following pseudocode might be ambiguous, but 
either case makes sense:

x = 1
def spam():
print x  # prints 1
x = 2  # does this create a new local x, or modify the old global x?
print x  # unambiguously prints 2

print x  # prints 1 or 2


Python doesn't allow this, but another language might; in Python, a 
reasonable way to get similar behaviour might be:

x = 1
def spam():
print globals()['x']
x = 2  # unambiguously creates a new local x
print x  # unambiguously prints 2

print x  # unambiguously prints 1


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Steven D'Aprano
On Mon, 12 Dec 2011 04:21:15 -0800, Eelco wrote:

>> No more, or less, explicit than the difference between "==" and "is".
> 
> == may be taken to mean identity comparison; 'equals' can only mean one
> thing.

Nonsense. "Equals" can be taken to mean anything the language designer 
chooses, same as "==". There is no language police that enforces The One 
True Meaning Of Equals. In fact, there is no one true meaning of equals. 
Even my tiny Pocket Oxford dictionary lists five definitions.

It is ironic that the example you give, that of identity, is the standard 
definition of equals in mathematics. 2*2 = 4 does not merely say that 
"there is a thing, 2*2, which has the same value as a different thing, 
4", but that both sides are the same thing. Two times two *is* four. All 
numbers are, in some sense, singletons and equality implies identity.

A language designer might choose to define equals as an identity test, or 
as a looser "values are the same" test where the value of an object or 
variable is context dependent, *regardless* of how they are spelled: = == 
=== "is" "equals" or even "flibbertigibbet" if they wanted to be 
whimsical. The design might allow types to define their own sense of 
equality.

Triangle.equals(other_triangle) might be defined to treat any two 
congruent triangles as equal; set equality could be defined as an 
isomorphism relation; string equality could be defined as case-
insensitive, or to ignore leading and trailing whitespace. Regardless of 
whether you or I *would* make those choices, we *could* make those 
choices regardless of how our language spells the equality test.


> Of course 'formally' these symbols are well defined, but so is
> brainf*ck

I don't understand your point here.



>>  Modulo is hardly an obscure operation. "What's the remainder...?" is a
>>  simple question that people learn about in primary school.
> 
> 
> So is 'how much wood would a woodchucker chuck if a woodchucker could
> chuck wood?'. But how often does that concept turn up in your code?

You didn't make a statement about how often modulo turns up in code 
(which is actually quite frequently, and possibly more frequently than 
regular division), but about the obscurity of the operation. Taking the 
remainder is not an obscure operation. The names "modulo" and "modulus" 
may be obscure to those who haven't done a lot of mathematics, but the 
concept of remainder is not. "How many pieces are left over after 
dividing into equal portions" is something which even small children get.


>> And you can blame C for the use of % instead of mod or modulo.
> 
> I didnt know one of Python's design goals was backwards compatibility
> with C.

Don't be silly. You know full well Python is not backwards compatible 
with C, even if they do share some syntactical features.

C is merely one of many languages which have influenced Python, as are 
Haskell, ABC, Pascal, Algol 68, Perl (mostly in the sense of "what not to 
do" ), Lisp, and probably many others. It merely happens that C's 
use of the notation % for the remainder operation likely influenced 
Python's choice of the same notation.

I note that the *semantics* of the operation differs in the two 
languages, as I understand that the behaviour of % with negative 
arguments is left undefined by the C standard, while Python does specify 
the behaviour.


>>  I can't imagine what sort of Python code you have seen that you
>>  consider 90% attribute access "typical". I've just run the Python
>>  tokenizer over my startup.py file, and I get these results:
> 
> Yes, that was a hyperbole; but quite an often used construct, is it not?

It's hard, but not quite impossible, to write useful Python code without 
it, so yes.

 
>>  If you can supply any function at all, what happens if I write this:
> 
> 
> You cannot; only constructors modelling a sequence or a dict, and only
> in that order. Is that rule clear enough?

But why limit yourself to those restrictive rules?

If I want to collect a sequence of arguments into a string, why shouldn't 
I be allowed to write this?

def func(parg, str(args)): ...

If I want to sum a collection of arguments, why not write this?

def func(pargs, sum(args)): ...

Isn't that better than this?

def func(pargs, *args):
args = sum(args)
...


But no. I don't mean those examples to be taken seriously: when you 
answer to your own satisfaction why they are bad ideas, you may be closer 
to understanding why I believe your idea is also a bad idea.



>> I believe that your proposal leads to an over-generalisation "call
>> arbitrary functions when handling parameter lists".
> 
> I hope the above clears that up. It is as much about calling functions
> as ** is about raising kwargs to the power of.

I don't understand this comment. Nobody has suggested that ** in function 
parameter lists is the exponentiation operator.

As for "calling functions", how else do you expect to generate a type if 
you don't call the ty

Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Chris Angelico
On Tue, Dec 13, 2011 at 1:43 PM, Steven D'Aprano
 wrote:
> It merely happens that C's
> use of the notation % for the remainder operation likely influenced
> Python's choice of the same notation.

Considering that Python also had the notion that "integer divided by
integer yields integer" until Py3, I would say it's extremely likely
that most of Python's division facilities were modelled off C. That's
not a bad thing; gives you a set of operations that a large number of
people will grok, and only a small number of oddities.

> I note that the *semantics* of the operation differs in the two
> languages, as I understand that the behaviour of % with negative
> arguments is left undefined by the C standard, while Python does specify
> the behaviour.

... and there's the proof that "modelled off" does not mean "slavishly
follows". This lack of definition is a weakness in C.

> def foo(a, 2*b+1, c):  # double the second arg and add 1

No, that should subtract 1 from the second arg and halve it. The
expression you give there has to match the value from the parameter
list.

This syntax would be a huge boon to Python. Imagine how much easier
this could make things:

def foo(sum(x)):
return x

print(foo(120)) # will print a list of numbers that sum to 120


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


Re: Verbose and flexible args and kwargs syntax

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 7:43 PM, Steven D'Aprano
 wrote:
> If I want to collect a sequence of arguments into a string, why shouldn't
> I be allowed to write this?
>
>    def func(parg, str(args)): ...

Obviously, because the correct syntax would be:

def func(parg, ''.join(args)): ...

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


Re: Overriding a global

2011-12-12 Thread Ian Kelly
On Mon, Dec 12, 2011 at 4:48 PM, Joshua Landau
 wrote:
> Rebinding logger locally in a function is really no
> different to a subclass rebinding a variable from its main class using that
> class' value. The only difference is that, in that case, you have an
> alternate binding to the original value.

No, there is another difference, the reason for rebinding the name.
In a subclass, you would rebind a class attribute because that
particular attribute, which you need to change, is used and expected
by external code, either in the base class or in code that uses its
API (or both).  Local variables in functions, on the other hand, are
not externally visible, so there is no need to do this in order to
conform to the expectations of external code.  All it does in that
case is to sow potential confusion.
-- 
http://mail.python.org/mailman/listinfo/python-list