Re: Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread dieter
Peter Otten <__pete...@web.de> writes:

> Lawrence D’Oliveiro wrote:
>
>> On Tuesday, June 28, 2016 at 5:03:08 PM UTC+12, Ben Finney wrote:
>> 
>>> I would like to see a more Pythonic, more explicit and expressive
>>> replacement with its component parts easily understood.
>> 
>> I don’t know why this fear and suspicion of lambdas is so widespread among
>> Python users ... former Java/C# programmers, perhaps?

Maybe, it's the name ("lambda").

In Javascript, anonymous functions are widespread (and extensively
used for e.g. callback definitions) - but it uses the much more familiar
"function" (rather than "lambda") for this purpose.

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


Re: Creating a calculator

2016-07-01 Thread Chris Warrick
On 1 July 2016 at 05:08, Elizabeth Weiss  wrote:
> while True:
> print("Options:")
> print("Enter 'add' to add two numbers")
> print("Enter 'subtract' to subtract two numbers")
> print("Enter 'multiply' to multiply two numbers")
> print("Enter 'divide' to divide two numbers")
> print("Enter 'quit' to end the program")
> user_input=input(":")
> if user_input=="quit":
> break
> elif user_input=="add":
> num1=float(input("Enter a number"))
> num2=float(input("Enter another number"))
> result=str(num1+num2)
> print("The answer is"+ result)
> elif user_input=="subtract":
> num1=float(input("Enter a number"))
> num2=float(input("Enter another number"))
> result=str(num1-num2)
> print("The answer is"+result)
>
> Two questions:
> 1. Why do I need to put ' ' around the words add, subtract, multiply, quit, 
> etc. when it is already in quotes in print()? When the calculator asks me 
> which option I would like to choose I do not write 'add'- I only write add.

This is used for display. The single quotes will be displayed as part
of the string. This is so that people notice the commands, for
example.

>>> print("Enter 'add' to add two numbers")
Enter 'add' to add two numbers
>>> print("Enter add to add two numbers")
Enter add to add two numbers
>>> print('Enter "add" to add two numbers')
Enter "add" to add two numbers

> 2. The program I am using to help me learn python mentions that the output 
> line could be put outside the if statements to omit repetition of code. What 
> does this mean and how would I write the code differently according to this?

Look at your current code. The following three lines appear twice (and
will appear 4 times if you add multiplication and division):

> num1=float(input("Enter a number"))
> num2=float(input("Enter another number"))
> print("The answer is"+ result)

This is code repetition. It’s discouraged, because if you have 4
copies of a longer segment, and you want to change something, you
would have to remember to change it in 4 places. In this case, you can
avoid code reuse like this:

1. Check if user said 'quit', and if yes, break from the loop. (Ignore
invalid input for now)
2. Ask the user for two numbers.
3. Make an if/elif/else structure to calculate the result.
4. Print out the result outside of `if`.

Example for 3. and 4.:
if user_input == 'add':
result = num1 + num2  # no need to call str() if you use commas in print()
elif user_input == 'subtract':
result = num1 - num2
# other elif clauses go here
print("The result is", result)

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Pierre-Alain Dorange
DFS  wrote:

> Here's a related program that doesn't require you to tell it what type
> of operation to perform.  Just enter 'num1 operator num2' and hit Enter,
> and it will parse the entry and do the math.
> 
> ---
> ui=raw_input('Enter calculation to perform: ')
> n1=float(ui.split(' ')[0])
> op=ui.split(' ')[1]
> n2=float(ui.split(' ')[2])
> if op=='+':c=n1+n2
> if op=='-':c=n1-n2
> if op=='*':c=n1*n2
> if op=='/':c=n1/n2
> print(ui+' = '+str(c))
> ---

More reduced :
--
u=raw_input('Enter calculation:")
print eval(u)
--
works and compute :
1+2+3+4-1+4*2
2+3.0/2-0.5

Perform better and shorter, but less educationnal of course...

-- 
Pierre-Alain Dorange   Moof 

Ce message est sous licence Creative Commons "by-nc-sa-2.0"

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


Need help in python program

2016-07-01 Thread Archana Sonavane
Hello Everyone,

I am doing python code by using API. 

My first API giving fields - Itemid, clock and value
second API giving fields - Itemid, key, units and delay

using for loops for both API.

Could you please tell me how to compare both id by using equal operator. 

My output should be :

Itemid, clock, value, key, units and delay
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Chris Warrick
On 1 July 2016 at 11:34, Pierre-Alain Dorange
 wrote:
> DFS  wrote:
>
>> Here's a related program that doesn't require you to tell it what type
>> of operation to perform.  Just enter 'num1 operator num2' and hit Enter,
>> and it will parse the entry and do the math.
>>
>> ---
>> ui=raw_input('Enter calculation to perform: ')
>> n1=float(ui.split(' ')[0])
>> op=ui.split(' ')[1]
>> n2=float(ui.split(' ')[2])
>> if op=='+':c=n1+n2
>> if op=='-':c=n1-n2
>> if op=='*':c=n1*n2
>> if op=='/':c=n1/n2
>> print(ui+' = '+str(c))
>> ---
>
> More reduced :
> --
> u=raw_input('Enter calculation:")
> print eval(u)
> --
> works and compute :
> 1+2+3+4-1+4*2
> 2+3.0/2-0.5
>
> Perform better and shorter, but less educationnal of course...

No, this is awful. It’s a great way to compromise your system’s
security. Never use eval() for any reason, especially with user input
— if you were to type in __import__('os').system('…') with some
particularly dangerous command (rm, format, …), you would kill your
system.

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jun 30, 2016, at 11:42 PM, Jussi Piitulainen 
>  wrote:
> 
> DFS writes:
> 
>> Here's a related program that doesn't require you to tell it what type
>> of operation to perform.  Just enter 'num1 operator num2' and hit
>> Enter, and it will parse the entry and do the math.
>> 
>> ---
>> ui=raw_input('Enter calculation to perform: ')
>> n1=float(ui.split(' ')[0])
>> op=ui.split(' ')[1]
>> n2=float(ui.split(' ')[2])
>> if op=='+':c=n1+n2
>> if op=='-':c=n1-n2
>> if op=='*':c=n1*n2
>> if op=='/':c=n1/n2
>> print(ui+' = '+str(c))
>> ---
> 
> I use multiple assignment a lot, like this:
> 
>n1, op, n2 = ui.split()
> 
> It's not only compact, it also crashes if there are more elements than
> expected, and I want it to crash when that happens. Or rather, I prefer
> a crash to silence when input is bad.
> 
> For the calculator, it may be better to split on any whitespace and
> discard empty strings, which is what ui.split() does. Splitting on a
> single space seems unnecessarily strict in a calculator (whereas
> splitting on a single tab is what I very much do in my work - the data
> formats are such).
> 
> I think multiple assignment is good even for a beginner. Perhaps do it a
> second time straight away:
> 
>n1, op, n2 = ui.split()
>n1, n2 = float(n1), float(n2)
> 
> But it's only with the split where it really pays.
> 
>n1, op, n2 = ui.split()
>n1 = float(n1)
>n2 = float(n2)
> 
> The latter might be even preferable. Hm.
> 
>n1, n2 = map(float, (n1, n2))
> 
> :)

For my BASIC interpreter, each line of BASIC is broken this way into tokens.

line_number, keyword, *expression = line.split(' ', 2)

For a line like 10 PRINT "HELLO, WORLD!", this works as expected.

For a line like 20 END, which doesn't have a third element for expression, an 
empty list is assigned.

By using * to unpack the split line, my program no longer crashes and no 
try/except block is needed to work around the crash. A later line of code will 
test the expression, ignore if empty or run regex if full. 

Chris R.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Jussi Piitulainen
Christopher Reimer writes:

> For my BASIC interpreter, each line of BASIC is broken this way into
> tokens.
>
> line_number, keyword, *expression = line.split(' ', 2)
>
> For a line like 10 PRINT "HELLO, WORLD!", this works as expected.
>
> For a line like 20 END, which doesn't have a third element for
> expression, an empty list is assigned.
>
> By using * to unpack the split line, my program no longer crashes and
> no try/except block is needed to work around the crash. A later line
> of code will test the expression, ignore if empty or run regex if
> full.

Yes.

Consider line.split(None, 2) or line.split(maxsplit=2). You may still
need to strip the third component, but at least it will *be* the third
component even if the user happens to type extra spaces like this:

10   PRINT  "Hello, world."

And you won't get a spurious third component if the user types this:

20 END   

(There's trailing spaces.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Pierre-Alain Dorange
Chris Warrick  wrote:

> > More reduced :
> > --
> > u=raw_input('Enter calculation:")
> > print eval(u)
> > --
> > works and compute :
> > 1+2+3+4-1+4*2
> > 2+3.0/2-0.5
> >
> > Perform better and shorter, but less educationnal of course...
> 
> No, this is awful. It's a great way to compromise your system's
> security. Never use eval() for any reason, especially with user input
> — if you were to type in __import__('os').system('…') with some
> particularly dangerous command (rm, format, …), you would kill your
> system.

Yes you're right, eval can be really dangerous.
You could make it (a little) safer using env ; but a hacker could always
break things with eval.

-
env={}
env["__builtins__"] = None

u=raw_input('Enter calculation:")
print eval(u,env)
-

-- 
Pierre-Alain Dorange   Moof 

Ce message est sous licence Creative Commons "by-nc-sa-2.0"

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


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jul 1, 2016, at 5:46 AM, Jussi Piitulainen  
> wrote:
> 
> Christopher Reimer writes:
> 
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
>> 
>> line_number, keyword, *expression = line.split(' ', 2)
>> 
>> For a line like 10 PRINT "HELLO, WORLD!", this works as expected.
>> 
>> For a line like 20 END, which doesn't have a third element for
>> expression, an empty list is assigned.
>> 
>> By using * to unpack the split line, my program no longer crashes and
>> no try/except block is needed to work around the crash. A later line
>> of code will test the expression, ignore if empty or run regex if
>> full.
> 
> Yes.
> 
> Consider line.split(None, 2) or line.split(maxsplit=2). You may still
> need to strip the third component, but at least it will *be* the third
> component even if the user happens to type extra spaces like this:
> 
> 10   PRINT  "Hello, world."
> 
> And you won't get a spurious third component if the user types this:
> 
> 20 END   
> 
> (There's trailing spaces.)

This is a BASIC interpreter. Any extra spaces for line_number or keyword will 
raise an incomprehensible syntax error, as the line number must convert to an 
integer and the keyword much match the KEYWORDS list. As for trailing spaces 
for expression, regex will keep them whole if enclosed in double quotes or 
convert them to a list element. Depending on the keyword grammar, extra spaces 
are likely to be ignored.

A C interpreter would be more difficult as the same line of code could be 
written several different ways and be valid.

FILE *source
FILE * source
FILE* source
FILE*source

The first line is how I normally see this statement written. The last line I 
found in a 1991 book with a strange dialect of C that I've never seen before 
and doesn't always compile correctly without modification. Writing a C 
interpreter is not on my to do list. 

Chris R.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Jussi Piitulainen
Christopher Reimer writes:

>> On Jul 1, 2016, at 5:46 AM, Jussi Piitulainen wrote:
>> 
>> Christopher Reimer writes:
>> 
>>> For my BASIC interpreter, each line of BASIC is broken this way into
>>> tokens.
>>> 
>>> line_number, keyword, *expression = line.split(' ', 2)
>>> 
>>> For a line like 10 PRINT "HELLO, WORLD!", this works as expected.
>>> 
>>> For a line like 20 END, which doesn't have a third element for
>>> expression, an empty list is assigned.
>>> 
>>> By using * to unpack the split line, my program no longer crashes and
>>> no try/except block is needed to work around the crash. A later line
>>> of code will test the expression, ignore if empty or run regex if
>>> full.
>> 
>> Yes.
>> 
>> Consider line.split(None, 2) or line.split(maxsplit=2). You may still
>> need to strip the third component, but at least it will *be* the third
>> component even if the user happens to type extra spaces like this:
>> 
>> 10   PRINT  "Hello, world."
>> 
>> And you won't get a spurious third component if the user types this:
>> 
>> 20 END   
>> 
>> (There's trailing spaces.)
>
> This is a BASIC interpreter. Any extra spaces for line_number or
> keyword will raise an incomprehensible syntax error, as the line
> number must convert to an integer and the keyword much match the
> KEYWORDS list. As for trailing spaces for expression, regex will keep
> them whole if enclosed in double quotes or convert them to a list
> element. Depending on the keyword grammar, extra spaces are likely to
> be ignored.

You get to decide!

(But if you split on whitespace as I suggested, there won't be any extra
spaces in the line number or keyword. While if you split on every single
space, the first and second component of the split may not even contain
the intended line number and keyword. Try it. Then do what you like.)

> A C interpreter would be more difficult as the same line of code could
> be written several different ways and be valid.
>
> FILE *source
> FILE * source
> FILE* source
> FILE*source
>
> The first line is how I normally see this statement written. The last
> line I found in a 1991 book with a strange dialect of C that I've
> never seen before and doesn't always compile correctly without
> modification. Writing a C interpreter is not on my to do list.

C syntax is not line-oriented anyway. It's semicolon-oriented.

Good luck with your BASIC interpreter. (No sarcasm or anything like
that. I think it's a nice project.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-01 Thread Steven D'Aprano
On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:

> For my BASIC interpreter, each line of BASIC is broken this way into
> tokens.
[...]
> By using * to unpack the split line, my program no longer crashes and no
> try/except block is needed to work around the crash. A later line of code
> will test the expression, ignore if empty or run regex if full.

I wish you wouldn't describe this as "crash".

The Python interpreter should never crash. That would be a segmentation
fault, and that is considered to be a very serious bug.

But *raising an exception* is another story. Raising exceptions is not a
crash, it is the interpreter working as expected. This statement:

line_number, keyword, expr = "20 END".split(' ', 2)

is SUPPOSED to raise an exception, if it didn't, the interpreter would be
broken. To call that a "crash" is horribly misleading.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Namespaces are one honking great idea

2016-07-01 Thread Steven D'Aprano
The Zen of Python says:

Namespaces are one honking great idea -- let's do more of those!



Proposal
=

Add a new "namespace" object to Python.


Rationale
==

Sometimes we have a group of related functions and variables that belong
together, but are not sufficiently unrelated to the rest of the module that
we want to split them out into another file.

Python allows us to group related chunks of code in three levels of
grouping:

- the class, containing one of more variable and/or function (method);
- the module, containing one or more classes and/or functions;
- the package, containing one or more modules.

But classes are not like the others: they must be instantiated before they
can be used, and they are more than just a mere namespace grouping related
entities. Classes support inheritance. Classes should be used for "is-a"
relationships, not "has-a" relationships. Although classes (and instances)
are namespaces, they provide fundamentally different kind of behaviour than
modules and packages.

Sometimes we have a group of related functions which belongs together, but
they are more closely related to each other than they are to the rest of
the module, but not so distantly unrelated that they should be split off
into a separate module. Nor do they belong as a class -- there's nothing
analogous to an instance, and no need for inheritance.

Perhaps the functions have some name clashes, e.g. two different functions
that deserve the same name, or perhaps they're just conceptually related.

What is needed is a module inside a module, but without the necessity of
refactoring the code into a package and splitting the code out into a
separate file. In other words, something rather like C++ namespaces:

https://msdn.microsoft.com/en-us/library/5cb46ksf.aspx


Proof of concept
=

Here's a proof of concept. I use a class with a custom metaclass like this:


# Python 3 version
class ExampleNS(metaclass=Namespace):
x = 1
y = []

def spam(n):
return 'spam'*n

z = spam(3).upper()

def ham(n):
return spam(n).replace('sp', 'H')

def test():
global x
x += 1
y.append(1)
return x, y


And a demonstration of its use:

py> Example.spam(5)
'spamspamspamspamspam'
py> Example.ham(5)
'HamHamHamHamHam'
py> Example.test()
(2, [1])
py> Example.test()
(3, [1, 1])
py> print(Example.x, Example.y, Example.z)
3 [1, 1] SPAMSPAMSPAM

Despite the "class" statement (a limitation of Python's lack of dedicated
syntax for namespaces), the Example namespace behaves like (in fact, *is*)
a module embedded inside a module.

Notice that the functions are not methods and don't require a "self"
parameter. Being functions, they can be used inside the body of the
namespace, including inside other functions.

Outside the namespace, access is via dotted attribute: Example.spam. But
inside it, functions can refer to each other without knowing the name of
their namespace.

Especially note that inside the namespace, the global statement makes a name
refer to the namespace scope.


Implementation
===

Here's a simplified implementation:


from types import FunctionType, ModuleType

class NamespaceType(ModuleType):
def __repr__(self):
return 'namespace <%s>' % self.__name__

class Namespace(type):
def __new__(meta, name, bases, ns):
if bases != ():
raise RuntimeError("namespaces cannot inherit")
module = NamespaceType(name)
globals_ = module.__dict__
if '__builtins__' not in globals_:
globals_['__builtins__'] = globals()['__builtins__']
for name, obj in ns.items():
if type(obj) is FunctionType:
ns[name] = meta._copy_and_inject(obj, globals_)
module.__dict__.update(ns)
return module

@classmethod
def _copy_and_inject(meta, func, globals):
"""Return a new function object with the given globals."""
assert type(func) is FunctionType
f = FunctionType(
func.__code__, globals, func.__name__,
 func.__defaults__, func.__closure__)
f.__dict__ = func.__dict__
# Next two lines are Python 3 only.
f.__kwdefaults__ = func.__kwdefaults__
f.__annotations__ = func.__annotations__
return f



The namespace object itself is actually a module (to be precise, a subclass
of ModuleType). The Namespace metaclass returns a new module object,
containing all the names I defined inside the class, after modifying any
function objects to treat the new module object as their globals.


Unresolved questions
=

Would a decorator be better than a metaclass?

@namespace
class Example:
...


How about a mechanism to exclude functions from having their globals
changed?


Some limitations
=

The simplified implementation shown doesn't allow functions inside the
namespace to access names outside of the nam

Re: Can math.atan2 return INF?

2016-07-01 Thread Rustom Mody
On Thursday, June 30, 2016 at 11:33:58 PM UTC+5:30, Steven D'Aprano wrote:
> On Fri, 1 Jul 2016 01:28 am, Rustom Mody wrote:
> 
> > On Thursday, June 30, 2016 at 1:55:18 PM UTC+5:30, Steven D'Aprano wrote:
> > 
> >> you state that Turing "believes in souls" and that he "wishes to
> >> put the soul into the machine" -- what do his religious beliefs have to
> >> do with his work?
> > 
> > Bizarre question -- becomes more patently ridiculous when put into general
> > form "What does what I do have to do with what I believe?"
> 
> Lots of people do things that go against their beliefs, or their beliefs (at
> least, their professed beliefs) go against what they do. But I'll ask
> again: in what way does Turing's supposed beliefs about souls have anything
> to do with his mathematical work?
> 
> Let's be concrete:
> 
> In what way does the Halting Problem depend on the existence (or
> non-existence) of the soul?

Lets change your question -- ever so slightly, given the Turing-context: 

In what way does the Turing Test depend on the existence (or non-existence) of 
the soul?

> 
> How was his work on breaking German military codes during World War 2
> reliant on these supposed souls? (In the sense of a separate, non-material
> spirit, not in the figurative sense that all people are "souls".)

When you say "soul" you (seem to?) mean what has been called with justifiable
derision, "dualistic notion of soul"
- something for which Christianity gets bad press though its the invention of 
Descartes
http://www.iep.utm.edu/descmind/
- something which caught on because of Descartes huge reputation as a scientist

There are other more reasonable non-religious non-dualistic notions of soul 
possible:

http://www.bu.edu/agni/poetry/print/2002/56-szymborska.html



You are missing the point -- its not about specific numbers its about 
cardinality not adding up

- Cantor theory points to uncountably many real numbers
- All the sets upto algebraic are countable
- So the uncountable fellas need to be transcendental
- We only know two blessed guys -- π and e

Where are all the others hiding??

And dont try saying that if e is transcendental so is 2e 3e 4e...
And no use trying more such tricks -- they only multiply these two countably 
infinite times
And you may produce a few more, more esoteric transcendentals --- a very
finite set!

Nor is it much good saying this is not much relevance to our field:
https://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument

So our (computer scientists') predicament in short

- our field is opposed to Cantor's non-constructivist *outlook*
- At the foundation of CS are *methods* that come from Cantor... OOPS!
-- 
https://mail.python.org/mailman/listinfo/python-list


super and mix-in class: how exactly is the search order altered?

2016-07-01 Thread Veek. M
I had posted this on StackOverflow - it's an excellent example of why SO 
sucks (don't want that happening here so please read carefully):

http://stackoverflow.com/questions/38145818/super-and-mix-in-class-how-exactly-is-the-search-order-altered?noredirect=1#comment63722336_38145818


I'm reading this article: 
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

He's trying to explain the purpose of a 'mix-in class' and he says

We did not alter the source code for LoggingDict. Instead we built a 
subclass whose only logic is to compose two existing classes and control 
their search order.

class LoggingOD(LoggingDict, collections.OrderedDict):
pass

My question is this: in the above article context, is he talking about 
the LoggingDict's search order that is being manipulated? Or he is 
talking about manipulating the LoggingOD search order?

He says very clearly "not alter the source code for LoggingDict" so 
clearly he means that somehow, magically - the search order for 
super().__setitem__ in

class LoggingDict(dict):
def __setitem__(self, key, value):
logging.info('Settingto %r' % (key, value))
super().__setitem__(key, value)

is being altered/influenced, but how? Could someone clarify what exactly 
is going on here? Far as I can make of it, the tree looks like this: 
http://i.stack.imgur.com/3foOB.jpg

Here's the code:
import collections

class LoggingDict(dict):
def __setitem__(self, key, value):
logging.info('Settingto %r' % (key, value))
super().__setitem__(key, value)

class LoggingOD(LoggingDict, collections.OrderedDict):
pass

x = LoggingDict()
print LoggingDict.__mro__
print LoggingOD.__mro__

as you can see.. 

selfstudy@deathstar:~$ python 29.mro.py 
(, , )
(, , , , )
selfstudy@deathstar:~$ 

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


Re: Creating a calculator

2016-07-01 Thread alister
On Fri, 01 Jul 2016 23:52:45 +1000, Steven D'Aprano wrote:

> On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:
> 
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
> [...]
>> By using * to unpack the split line, my program no longer crashes and
>> no try/except block is needed to work around the crash. A later line of
>> code will test the expression, ignore if empty or run regex if full.
> 
> I wish you wouldn't describe this as "crash".
> 
> The Python interpreter should never crash. That would be a segmentation
> fault, and that is considered to be a very serious bug.
> 
> But *raising an exception* is another story. Raising exceptions is not a
> crash, it is the interpreter working as expected. This statement:
> 
> line_number, keyword, expr = "20 END".split(' ', 2)
> 
> is SUPPOSED to raise an exception, if it didn't, the interpreter would
> be broken. To call that a "crash" is horribly misleading.

i think this one is a matter of symantics
you are correct that the Python interpreter has not crashed but the op 
could also be considered correct is saying that HIS program has crashed.

As a child I had many programs "crash" in this way on my Commodore 64 
without killing the basic interpreter (at-least not until I started to 
include machine code ;-) ) 




-- 
Technology is dominated by those who manage what they do not understand.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Random832
On Fri, Jul 1, 2016, at 10:13, Steven D'Aprano wrote:
> The biggest limitation is that I have to abuse the class statement to do
> this. In an ideal world, there would be syntactic support and a keyword:
> 
> namespace Example:
> x = 0
> y = []
> def test(n): ...
> 
> although others might argue that *not* needing a dedicated keyword is, in
> fact, better.

What might be nice would be a single syntax that isn't specific to
classes or your "namespaces".

namespace(type) Name:
   "equivalent to class Name:"

namespace(whatever) Name:
   "equivalent to class Name(metaclass=whatever)"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread BartC

On 01/07/2016 15:13, Steven D'Aprano wrote:


Sometimes we have a group of related functions and variables that belong
together, but are not sufficiently unrelated to the rest of the module that
we want to split them out into another file.



Here's a proof of concept. I use a class with a custom metaclass like this:


# Python 3 version
class ExampleNS(metaclass=Namespace):
x = 1
y = []

def spam(n):
return 'spam'*n



py> Example.spam(5)
'spamspamspamspamspam'



Why not just extend the capabilities of a class? I actually thought this 
would work until I tried it and it didn't:


class C():
def fn():
print ("Hi!")

C.fn()

The error message suggests Python knows what's going on. So why not just 
make it work?


(The main issue would be, if an instance X of C /was/ created, then 
X.fn() wouldn't work as there is no 'self' parameter for fn.)


--
Bartc

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


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jul 1, 2016, at 6:52 AM, Steven D'Aprano  wrote:
> 
>> On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:
>> 
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
> [...]
>> By using * to unpack the split line, my program no longer crashes and no
>> try/except block is needed to work around the crash. A later line of code
>> will test the expression, ignore if empty or run regex if full.
> 
> I wish you wouldn't describe this as "crash".
> 
> The Python interpreter should never crash. That would be a segmentation
> fault, and that is considered to be a very serious bug.
> 
> But *raising an exception* is another story. Raising exceptions is not a
> crash, it is the interpreter working as expected. This statement:
> 
>line_number, keyword, expr = "20 END".split(' ', 2)
> 
> is SUPPOSED to raise an exception, if it didn't, the interpreter would be
> broken. To call that a "crash" is horribly misleading.

Where did I write that the Python interpreter had "crashed"?

I wrote that *my program* crashed and I found an elegant solution to prevent 
the crashing from happening in the first place that doesn't require a 
try/except block.

Chris R.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can math.atan2 return INF?

2016-07-01 Thread Marko Rauhamaa
Rustom Mody :

> There are other more reasonable non-religious non-dualistic notions of
> soul possible:

Software engineers should have an easy time understanding what a soul
is: a sufficiently sophisticated software system in execution. I'd say
the minimum requirement for a soul is the capacity to suffer. I don't
think anything built by humans has yet reached that level of
sophistication, but insects probably can feel pain as authentically as
humans.

> - Cantor theory points to uncountably many real numbers
> - All the sets upto algebraic are countable
> - So the uncountable fellas need to be transcendental
> - We only know two blessed guys -- π and e
>
> Where are all the others hiding??

Here: https://en.wikipedia.org/wiki/Transcendental_number>.

> And dont try saying that if e is transcendental so is 2e 3e 4e... And
> no use trying more such tricks -- they only multiply these two
> countably infinite times And you may produce a few more, more esoteric
> transcendentals --- a very finite set!

The banal way of putting it that we can express only countably many
individual items.

The more philosophical point of view is that mathematics failed at
circumscribing all of philosophy and is condemned to counting beans.
Naive set theory was a Grand Unified Theory of Everything, but of course
inconsistent. The bottom-up set theories are sane but completely fail at
being the ultimate metalevel.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Ethan Furman

On 07/01/2016 07:13 AM, Steven D'Aprano wrote:

I like the idea, but I have a couple questions about the design choices. 
 Comments below.



The Zen of Python says:

 Namespaces are one honking great idea -- let's do more of those!



Proposal
=

Add a new "namespace" object to Python.




Proof of concept
=

Here's a proof of concept. I use a class with a custom metaclass like this:


# Python 3 version
class ExampleNS(metaclass=Namespace):
 x = 1
 y = []

 def spam(n):
 return 'spam'*n

 z = spam(3).upper()

 def ham(n):
 return spam(n).replace('sp', 'H')

 def test():
 global x
 x += 1
 y.append(1)
 return x, y




Despite the "class" statement (a limitation of Python's lack of dedicated
syntax for namespaces), the Example namespace behaves like (in fact, *is*)
a module embedded inside a module.


So the idea is to have several "mini-modules" inside a single file?

Can a mini-module function access a different mini-module's function?

Can a mini-module function access/interact with the module's global scope?


Especially note that inside the namespace, the global statement makes a name
refer to the namespace scope.


Interesting.  :)



Unresolved questions
=

Would a decorator be better than a metaclass?


I think a decorator may provide more of a clue that something 
interesting is happening -- whether a decorator is feasible depends on 
whether you need the __prepare__ magic of metaclasses.



 @namespace
 class Example:
 ...


I believe Python already has a NameSpace type, so a different name is 
probably better.  How about minimodule? ;)




Some limitations
=

The simplified implementation shown doesn't allow functions inside the
namespace to access names outside of the namespace easily.


How not-easy is it?


In practice, the
user might want the name resolution order inside the namespace to be:

  local variables
  nonlocal variables
  namespace globals
  module globals
  builtins


That would be ideal, I think.  How close can we get to that?


The biggest limitation is that I have to abuse the class statement to do
this. In an ideal world, there would be syntactic support and a keyword:

 namespace Example:
 x = 0
 y = []
 def test(n): ...

although others might argue that *not* needing a dedicated keyword is, in
fact, better.


Metaclasses for the win!


Disadvantages
==

Those unfamiliar with the namespace concept may be confused by a class that
doesn't get instantiated.


A well-named decorator/base-class should help with that.


Did you mean for this to go to -Ideas?

--
~Ethan~

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


[ANN] pygcgen (github changelog generator)

2016-07-01 Thread topic2k--- via Python-list
Hello,

maybe you know "GitHub Changelog Generator" 
(https://github.com/skywinder/github-changelog-generator).

As i came across it, i liked to try it, but wasn't able to get it running. The 
script is written in Ruby. As i don't know Ruby, i had the idea to convert it 
to Python. After a few days of trial and error, learning a bit of Ruby and 
debugging, i finally had a working version: https://github.com/topic2k/pygcgen 
. Now i wanna ask you, if you would like to try pygcgen (as i called my 
version) and give me some feedback. I already tried some options, but the more 
people test it, the better can get it. :)

Currently it's only written to be compatible with Python 2.7. Any help in 
making it compatible with 2.7 and 3.5 would be appreciated.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Chris Angelico
On Sat, Jul 2, 2016 at 12:49 AM, BartC  wrote:
> Why not just extend the capabilities of a class? I actually thought this
> would work until I tried it and it didn't:
>
> class C():
> def fn():
> print ("Hi!")
>
> C.fn()
>
> The error message suggests Python knows what's going on. So why not just
> make it work?

rosuav@sikorsky:~$ python3
Python 3.6.0a2+ (default:57f3514564f6, Jun 29 2016, 16:27:34)
[GCC 5.3.1 20160528] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class C():
... def fn():
... print ("Hi!")
...
>>> C.fn()
Hi!
>>>

But if you have two such functions, they can't call each other without
the namespace marker.

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


Re: Namespaces are one honking great idea

2016-07-01 Thread Steven D'Aprano
On Sat, 2 Jul 2016 02:00 am, Ethan Furman wrote:

> On 07/01/2016 07:13 AM, Steven D'Aprano wrote:
> 
> I like the idea, but I have a couple questions about the design choices.

Thanks!

>   Comments below.


[...]
>> Despite the "class" statement (a limitation of Python's lack of dedicated
>> syntax for namespaces), the Example namespace behaves like (in fact,
>> *is*) a module embedded inside a module.
> 
> So the idea is to have several "mini-modules" inside a single file?

That would certainly be possible.


> Can a mini-module function access a different mini-module's function?

Yes, via the dotted attribute name, just as you might say "math.sin".

The only difference is that you don't use import to get access to the
(mini-)module. It's just there, defined in your own file.


> Can a mini-module function access/interact with the module's global scope?

Yes. I'm still experimenting with different implementations, but I have a
proof of concept working.


>> Especially note that inside the namespace, the global statement makes a
>> name refer to the namespace scope.
> 
> Interesting.  :)
> 
> 
>> Unresolved questions
>> =
>>
>> Would a decorator be better than a metaclass?
> 
> I think a decorator may provide more of a clue that something
> interesting is happening -- whether a decorator is feasible depends on
> whether you need the __prepare__ magic of metaclasses.

I don't think __prepare__ is needed.



>>  @namespace
>>  class Example:
>>  ...
> 
> I believe Python already has a NameSpace type, so a different name is
> probably better.  How about minimodule? ;)

I think you are thinking of "SimpleNamespace".

In any case, so long as my namespace lives in a different, er, namespace as
the other namespace, there's no conflict :-)

In the long term, I think my namespace (if accepted into the stdlib) would
belong in functools, collections or types. Perhaps even its own module. I
don't think this needs to be a built-in.



>> Some limitations
>> =
>>
>> The simplified implementation shown doesn't allow functions inside the
>> namespace to access names outside of the namespace easily.
> 
> How not-easy is it?

Not that hard now. I have an implementation working. It actually turned out
to be easy. (Thanks Raymond for ChainMap!)



>> In practice, the
>> user might want the name resolution order inside the namespace to be:
>>
>>   local variables
>>   nonlocal variables
>>   namespace globals
>>   module globals
>>   builtins
> 
> That would be ideal, I think.  How close can we get to that?

I now have that working, for some definition of working. Its not extensively
tested, so there might be some bugs or issues I haven't thought of, but the
basic concept is working: inside the namespace/mini-module object,
functions see namespace globals ahead of module globals, which are ahead of
builtins.


[...]
> Did you mean for this to go to -Ideas?


Not yet. I wanted some initial feedback to see if anyone else liked the idea
before taking it to Bikeshedding Central :-)

Besides, I expect Python-Ideas will say it needs to be a package on PpPI
first. Although I am kinda considering sneaking this into the std lib as an
undocumented internal feature, like simplegeneric in pkgutil. (Don't tell
anyone I said that *wink* )





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Creating a calculator

2016-07-01 Thread Jussi Piitulainen
Steven D'Aprano writes:

> On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:
>
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
> [...]
>> By using * to unpack the split line, my program no longer crashes and no
>> try/except block is needed to work around the crash. A later line of code
>> will test the expression, ignore if empty or run regex if full.
>
> I wish you wouldn't describe this as "crash".
>
> The Python interpreter should never crash. That would be a segmentation
> fault, and that is considered to be a very serious bug.
>
> But *raising an exception* is another story. Raising exceptions is not a
> crash, it is the interpreter working as expected. This statement:
>
> line_number, keyword, expr = "20 END".split(' ', 2)
>
> is SUPPOSED to raise an exception, if it didn't, the interpreter would
> be broken. To call that a "crash" is horribly misleading.

I think Christopher merely echoed my use of the word, so let me take the
blame.

But it's quite different to say "my program crashed" (didn't handle an
exception - fix program, or fix the input) and "the Python interpreter
crashed" (uh oh).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Steven D'Aprano
On Sat, 2 Jul 2016 12:49 am, BartC wrote:

> On 01/07/2016 15:13, Steven D'Aprano wrote:
> 
>> Sometimes we have a group of related functions and variables that belong
>> together, but are not sufficiently unrelated to the rest of the module
>> that we want to split them out into another file.
> 
>> Here's a proof of concept. I use a class with a custom metaclass like
>> this:
>>
>>
>> # Python 3 version
>> class ExampleNS(metaclass=Namespace):
>> x = 1
>> y = []
>>
>> def spam(n):
>> return 'spam'*n
> 
>> py> Example.spam(5)
>> 'spamspamspamspamspam'
> 
> 
> Why not just extend the capabilities of a class? 

The usual ways to change the behaviour of classes from Python code is via
decorator, which lets you modify the class after it is created, a
metaclass, which lets you modify it before it is created, or by using
descriptors to customize attribute access.

I'm using a metaclass. When you write:

class K: ...

that is syntactic sugar for calling the default metaclass (`type`) with some
arguments, and `type` then returns the new class K. But if you use a
metaclass (usually, but not necessarily a subclass of `type`) you can
customize the creation of the new class, or even return a completely
different object altogether. That's what I'm doing.

Why am I returning a module instead of a class? Because (1) conceptually a
namespace (in the C++ sense) is like a module; (2) classes have a whole lot
of expectations that aren't relevant to namespaces (like inheritance,
instantiation, "is-a", etc); and (3) it's easy to use a module, which
already provides most of the behaviour I want.


> I actually thought this 
> would work until I tried it and it didn't:
> 
> class C():
>  def fn():
>  print ("Hi!")
> 
> C.fn()

That actually will work in Python 3. (I had forgotten that.) In Python 2,
you have to inherit C from object, AND decorate fn with staticmethod:

class C(object):
@staticmethod
def fn():
print ("Hi!")


But for my use, that's not enough. I want this to work:

class Foo:
def f():
return g().upper()
def g():
return "hi!"


That is, Foo should behave as if it were a module imported from a file,
except without actually being imported from a file.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


what the heck this code is doing?

2016-07-01 Thread Basant Dagar
#See below code:

def lookup(d, keyval):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == keyval :
found = True
return None

trackID = lookup(entry, 'Track ID')

 
Below is the main part of input xml file data, it passes to lookup function:

Track ID369

what I don't get is. How in the world it returns value 369 for the variable 
'trackID'??
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: what the heck this code is doing?

2016-07-01 Thread John Gordon
In <3bbddafc-dcd6-4d5c-84f4-94077b5bc...@googlegroups.com> Basant Dagar 
 writes:

> def lookup(d, keyval):
> found = False
> for child in d:
> if found : return child.text
> if child.tag == 'key' and child.text == keyval :
> found = True
> return None

> trackID = lookup(entry, 'Track ID')

> Below is the main part of input xml file data, it passes to lookup function:

> Track ID369

> what I don't get is. How in the world it returns value 369 for the variable 
> 'trackID'??

It loops through the child items in entry, looking for one with a
'key' value of 'Track ID'.  If it finds one, it sets found=True and
loops one more time, returning the text of the *next* child element.

It depends on the 'key' element being directly followed by the 'integer'
element within entry.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: what the heck this code is doing?

2016-07-01 Thread Basant Dagar
On Friday, July 1, 2016 at 2:06:28 PM UTC-4, John Gordon wrote:
> In <3bbddafc-dcd6-4d5c-84f4-94077b5bc...@googlegroups.com> Basant Dagar 
>  writes:
> 
> > def lookup(d, keyval):
> > found = False
> > for child in d:
> > if found : return child.text
> > if child.tag == 'key' and child.text == keyval :
> > found = True
> > return None
> 
> > trackID = lookup(entry, 'Track ID')
> 
> > Below is the main part of input xml file data, it passes to lookup function:
> 
> > Track ID369
> 
> > what I don't get is. How in the world it returns value 369 for the variable 
> > 'trackID'??
> 
> It loops through the child items in entry, looking for one with a
> 'key' value of 'Track ID'.  If it finds one, it sets found=True and
> loops one more time, returning the text of the *next* child element.
> 
> It depends on the 'key' element being directly followed by the 'integer'
> element within entry.
> 
> -- 
> John Gordon   A is for Amy, who fell down the stairs
> gor...@panix.com  B is for Basil, assaulted by bears
> -- Edward Gorey, "The Gashlycrumb Tinies"

Awesome. Thank you John for the prompt response.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: what the heck this code is doing?

2016-07-01 Thread Basant Dagar

Awesome. Thank you John for the prompt response. 

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


Re: Need help in python program

2016-07-01 Thread Bob Gailer
On Jul 1, 2016 6:30 AM, "Archana Sonavane" 
wrote:
>
> Hello Everyone,
>
> I am doing python code by using API.
>
> My first API giving fields - Itemid, clock and value
> second API giving fields - Itemid, key, units and delay
>
> using for loops for both API.
>
> Could you please tell me how to compare both id by using equal operator.
>
> My output should be :
>
> Itemid, clock, value, key, units and delay

Please provide some sample input and the corresponding output. What do you
mean by API?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help in python program

2016-07-01 Thread Christian Gollwitzer

Am 01.07.16 um 12:26 schrieb Archana Sonavane:

Hello Everyone,

I am doing python code by using API.

My first API giving fields - Itemid, clock and value
second API giving fields - Itemid, key, units and delay

using for loops for both API.

Could you please tell me how to compare both id by using equal operator.

My output should be :

Itemid, clock, value, key, units and delay



I think you want a "join" operation from relational algebra. pandas can 
do that:


http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging

or you just store the one table in a dict with Itemd as the key and loop 
over the second, while looking up corresponding values from the dict.


Christin
--
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Ethan Furman

On 07/01/2016 10:10 AM, Steven D'Aprano wrote:

On Sat, 2 Jul 2016 02:00 am, Ethan Furman wrote:



Did you mean for this to go to -Ideas?


Not yet. I wanted some initial feedback to see if anyone else liked the idea
before taking it to Bikeshedding Central :-)

Besides, I expect Python-Ideas will say it needs to be a package on PpPI
first. Although I am kinda considering sneaking this into the std lib as an
undocumented internal feature, like simplegeneric in pkgutil. (Don't tell
anyone I said that *wink* )


Are there good use-cases for this in the stdlib?

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


Re: Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Ben Bacarisse
dieter  writes:

>> Lawrence D’Oliveiro wrote:

>>> I don’t know why this fear and suspicion of lambdas is so widespread among
>>> Python users ... former Java/C# programmers, perhaps?

By replying I'm not accepting the premise -- I have no idea if there is
widespread fear and suspicion of lambdas among Python users but it seems
unlikely.

> Maybe, it's the name ("lambda").
>
> In Javascript, anonymous functions are widespread (and extensively
> used for e.g. callback definitions)

Yes, but in Python they are restricted to a single expression.  It's
therefore quite likely that programmers who want the semantics of an
anonymous function just define a named function and use that instead.
That saves you from having to decide, up front, if an expression is
going to be enough or from having to change it later if you find that it
isn't.

> - but it uses the much more familiar
> "function" (rather than "lambda") for this purpose.

... or the new arrow notation.

-- 
Ben.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Lawrence D’Oliveiro
On Tuesday, June 28, 2016 at 5:03:08 PM UTC+12, Ben Finney wrote:
> There is a clever one-line decorator that has been copy-pasted without
> explanation in many code bases for many years::
> 
> decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda 
> func: decorator(func, *args, **kwargs)
> 

For those who want docstrings, I’ll give you docstrings:

def decorator_with_args(decorator) :
"given function decorator(func, *args, **kwargs), returns a decorator 
which," \
" given func, returns the result of decorator(func, *args, **kwargs)."

def decorate(*args, **kwargs) :

def generated_decorator(func) :
return \
decorator(func, *args, **kwargs)
#end generated_decorator

#begin decorate
generated_decorator.__name__ = 
"decorator_{}".format(decorator.__name__)
generated_decorator.__doc__ = "decorator which applies {} to the 
previously-specified arguments".format(decorator.__name__)
return \
generated_decorator
#end decorate

#begin decorator_with_args
decorate.__name__ = "decorate_with_{}".format(decorator.__name__)
decorate.__doc__ = "generates a decorator which applies {} to the given 
arguments".format(decorator.__name__)
return \
decorate
#end decorator_with_args
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Steven D'Aprano
On Sat, 2 Jul 2016 05:29 am, Ethan Furman wrote:

> On 07/01/2016 10:10 AM, Steven D'Aprano wrote:
>> On Sat, 2 Jul 2016 02:00 am, Ethan Furman wrote:
> 
>>> Did you mean for this to go to -Ideas?
>>
>> Not yet. I wanted some initial feedback to see if anyone else liked the
>> idea before taking it to Bikeshedding Central :-)
>>
>> Besides, I expect Python-Ideas will say it needs to be a package on PpPI
>> first. Although I am kinda considering sneaking this into the std lib as
>> an undocumented internal feature, like simplegeneric in pkgutil. (Don't
>> tell anyone I said that *wink* )
> 
> Are there good use-cases for this in the stdlib?

I have at least one.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Namespaces are one honking great idea

2016-07-01 Thread Kevin Conway
I believe the namespace object you are referring to is exactly a class.
IIRC, classes came about as a "module in a module".

Regardless, all use cases you've listed are already satisfied by use of the
static and class method decorators. Methods decorated with these do not
require an instance initialization to use.

On Fri, Jul 1, 2016, 20:17 Steven D'Aprano  wrote:

> On Sat, 2 Jul 2016 05:29 am, Ethan Furman wrote:
>
> > On 07/01/2016 10:10 AM, Steven D'Aprano wrote:
> >> On Sat, 2 Jul 2016 02:00 am, Ethan Furman wrote:
> >
> >>> Did you mean for this to go to -Ideas?
> >>
> >> Not yet. I wanted some initial feedback to see if anyone else liked the
> >> idea before taking it to Bikeshedding Central :-)
> >>
> >> Besides, I expect Python-Ideas will say it needs to be a package on PpPI
> >> first. Although I am kinda considering sneaking this into the std lib as
> >> an undocumented internal feature, like simplegeneric in pkgutil. (Don't
> >> tell anyone I said that *wink* )
> >
> > Are there good use-cases for this in the stdlib?
>
> I have at least one.
>
>
>
> --
> Steven
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Ben Finney
Ben Bacarisse  writes:

> By replying I'm not accepting the premise -- I have no idea if there
> is widespread fear and suspicion of lambdas among Python users but it
> seems unlikely.

I can testify, as the person who started this thread, that there is no
fear or suspicion of lambda here. I use it quite frequently without
qualm for creating self-explanatory functions that need no name.

Rather, the motivation was that a complex thing, with many moving parts,
has an unexplained implementation: a nested set of functions without
names to explain their part in the pattern.

That these are then immediately bound to a name, to me defeats the
purpose of using lambda in the first place. If you want a named
function, lambda is not the tool to reach for; we have the ‘def’
statement for that.

But by using ‘lambda’ the author avoided one of the more important parts
of publishing the code: making it readable and self-explanatory. If
they'd chosen a name for each function, that would at least have
prompted them to explain what they're doing.

So ‘lambda’ is great, and I use it without worry for creating simple
self-explanatory nameless functions. But it's not the right tool for
this job: This is not self-explanatory, and the component functions
should not be nameless.

-- 
 \   “It is forbidden to steal hotel towels. Please if you are not |
  `\  person to do such is please not to read notice.” —hotel, |
_o__)   Kowloon, Hong Kong |
Ben Finney

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


Re: Namespaces are one honking great idea

2016-07-01 Thread Rustom Mody
On Friday, July 1, 2016 at 8:19:36 PM UTC+5:30, BartC wrote:
> On 01/07/2016 15:13, Steven D'Aprano wrote:
> 
> > Sometimes we have a group of related functions and variables that belong
> > together, but are not sufficiently unrelated to the rest of the module that
> > we want to split them out into another file.
> 
> > Here's a proof of concept. I use a class with a custom metaclass like this:
> >
> >
> > # Python 3 version
> > class ExampleNS(metaclass=Namespace):
> > x = 1
> > y = []
> >
> > def spam(n):
> > return 'spam'*n
> 
> > py> Example.spam(5)
> > 'spamspamspamspamspam'
> 
> 
> Why not just extend the capabilities of a class? I actually thought this 
> would work until I tried it and it didn't:

Well I also thought similarly -- sure a normal (instance) method cannot be
used without an instance but sure this is what class/static methods are for?
ie Steven's option 4.

Then I remembered that python's LEGB rule is bizarre:
Outer scopes are added outside inner scopes ... except for classes
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-01 Thread Lawrence D’Oliveiro
On Saturday, July 2, 2016 at 1:50:56 PM UTC+12, Kevin Conway wrote:
> Regardless, all use cases you've listed are already satisfied by use of the
> static and class method decorators.

Except for the need to decorate every such function inside the class. How about:

import types

def namespace(inclass) :
"decorator which turns a class into a module."
outclass = types.ModuleType \
  (
name = inclass.__name__,
doc = inclass.__doc__,
  )
for attr in dir(inclass) :
if not attr.startswith("__") or attr in ("__package__",) :
setattr(outclass, attr, getattr(inclass, attr))
#end if
#end for
return \
outclass
#end namespace

Example use:

@namespace
class try_it :
"try it!"

val = "some text"

def func() :
print("func got called")
#end func

#end try_it
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Controlling the Mac OSX GUI via Python?

2016-07-01 Thread Lawrence D’Oliveiro
On Friday, July 1, 2016 at 4:59:11 PM UTC+12, Christian Gollwitzer wrote:
> Yes, simulating mouse clicks with 
> fixed coordinates etc. is prone to such failure, but there are better 
> methods. These mouse clicks and keyboard events usually trigger a method 
> call inside the GUI program. If there are any means to call that method 
> directly, you are independent from the graphics itself.

Even if you could get it working reliably, scripting a GUI is going to be slow.

GUIs are only designed to work at human speeds, after all.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why x is changed in the following program?

2016-07-01 Thread Veek. M
maurice.char...@telecom-paristech.fr wrote:

> from numpy import random
> x=random.randn(6)
> y=x
> y[0]=12
> print x[0]
> 
> 
> 

random.rand returns a list. x is a label to this list (container).
y=x creates another label to the same container/list.

y[0[ = 12 alters the 0th position of the container.
print x[0], uses a different label 'x' to change the same container.

use: y = list(x) to do a 'shallow copy' of x into a new list container
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subprocess startup error

2016-07-01 Thread Veek. M
Shweta Dinnimani wrote:

> hi
> 
> hello, I'm begineer to python programming.. I had installed python
> 3.5.1 version on my windows 7 system. I was fine earlier and now when
> i was trying the programs on string i'm facing the subprocess startup
> error. IDLE is not connecting. And python shell is also not opening. I
> tried uninstalling and installing the python shell but Im facing the
> problem.Please do help me
> 

You need to post/screen-capture the whole error message/traceback.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem using pickle

2016-07-01 Thread Veek. M
Nicky Mac wrote:

> Dear Python team,
> I have studied the excellent documentation, and attempted to make use
> of pickle thus:
> 
> filename = 'my_saved_adventure'
> import  pickle
> class object:
> def __init__(self,i,.t) :
> self.id   = i
>  .
> 
> class world:
> def __init__(self):
> self.object
> 
> class object:
> def __init__(self,i,
> 
> .then   Object instances of object are created 
> 
> myworld = world;
> myworld.Object = Object
> fileobj = open(filename,'wb')
> pickle.dump(myworld,fileobj); fileobj.close()
> result = "saved your game to " + filename
> 
> fileobj = open(filename,'rb')
> myworld = pickle.load(fileobj); fileobj.close()
> Object = myworld.Object
> result = "restored your game from " + filename
> 
> 
> The proecedures execute without error
> but a file of only 21b is created containing " ?c__main__world q .
> altho there are several k of object instance data.
> 

class Foo(object):
  pass

object is a keyword and you're using it as an identifier
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem using pickle

2016-07-01 Thread Rustom Mody
On Saturday, July 2, 2016 at 9:17:01 AM UTC+5:30, Veek. M wrote:
> object is a keyword and you're using it as an identifier

keyword and builtin are different
In this case though the advice remains the same
In general maybe not...
Just sayin'
-- 
https://mail.python.org/mailman/listinfo/python-list


JAR files into python

2016-07-01 Thread Joaquin Alzola
Hi Guys

I have the following script which will be used in Spark.

#!/usr/bin/env python3
from pyspark_cassandra import CassandraSparkContext, Row
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import os
os.environ['CLASSPATH']="/mnt/spark/lib"
conf = 
SparkConf().setAppName("test").setMaster("spark://192.168.23.31:7077").set("spark.cassandra.connection.host",
 "192.168.23.31")
sc = CassandraSparkContext(conf=conf)
sqlContext = SQLContext(sc)
df = 
sqlContext.read.format("org.apache.spark.sql.cassandra").options(keyspace="lebara_diameter_codes",
 table="nl_lebara_diameter_codes").load()
list = df.select("errorcode2001").where("errorcode2001 > 1200").collect()
list2 = df.select("date").collect()
print([i for i in list[0]])
print(type(list[0]))

The error that it throws is the following one (which is logical because I do 
not load the jar files):
py4j.protocol.Py4JJavaError: An error occurred while calling o29.load.
: java.lang.ClassNotFoundException: Failed to find data source: 
org.apache.spark.sql.cassandra. Please find packages at 
http://spark-packages.org

Is there a way to load those jar files into python or the classpath when 
calling sqlContext.read.format("org.apache.spark.sql.cassandra")?

BR

Joaquin
This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem using pickle

2016-07-01 Thread Ben Finney
"Veek. M"  writes:

> class Foo(object):
>   pass
>
> object is a keyword and you're using it as an identifier

Python does not have ‘object’ as a keyword. ‘and’ is a keyword.

Here's the difference::

>>> object

>>> object = "Lorem ipsum"
>>> object
'Lorem ipsum'

>>> and
  File "", line 1
and
  ^
SyntaxError: invalid syntax
>>> and = "Lorem ipsum"
  File "", line 1
and = "Lorem ipsum"
  ^
SyntaxError: invalid syntax

Here is how you can test whether a word is a Python keyword::

>>> import keyword
>>> keyword.iskeyword('object')
False
>>> keyword.iskeyword('and')
True

The set of keywords in Python is quite small.

>>> len(keyword.kwlist)
33

-- 
 \   “The best in us does not require the worst in us: Our love of |
  `\ other human beings does not need to be nurtured by delusion.” |
_o__) —Sam Harris, at _Beyond Belief 2006_ |
Ben Finney

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


Descriptor: class name precedence over instance name

2016-07-01 Thread Veek. M
Trying to make sense of this para:

--
Also, the attribute name used by the class to hold a descriptor takes
prece- dence over attributes stored on instances. 

In the previous example,
this is why the descriptor object takes a name parameter and why the
name is changed slightly by inserting a leading underscore. In order
for the descriptor to store a value on the instance, it has to pick a
name that is different than that being used by the descriptor itself
-
Under normal circumstances, when I do an attribute lookup:
x = Foo()
x.a
he will first check 'x' then Foo.

Is he say that Descriptors are a special case where Foo is checked 
first, then what - Base classes..? or does he hop back to look in the 
instance? How is C3 Linearization altered?


Additionally,
class Foo:
   def __init__(self, name, value):
 self.name = name

cannot be done because
x = Foo('bar', 10)

x.bar will..? attribute in class takes precedence.. great, isn't that 
what we want?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-01 Thread Ian Kelly
On Fri, Jul 1, 2016 at 10:27 PM, Veek. M  wrote:
> Trying to make sense of this para:
>
> --
> Also, the attribute name used by the class to hold a descriptor takes
> prece- dence over attributes stored on instances.
>
> In the previous example,
> this is why the descriptor object takes a name parameter and why the
> name is changed slightly by inserting a leading underscore. In order
> for the descriptor to store a value on the instance, it has to pick a
> name that is different than that being used by the descriptor itself
> -
> Under normal circumstances, when I do an attribute lookup:
> x = Foo()
> x.a
> he will first check 'x' then Foo.
>
> Is he say that Descriptors are a special case where Foo is checked
> first,

It depends whether it's a "data descriptor" or not. A data descriptor
is one that defines at least one of __set__ or __delete__, not just
__get__. Data descriptors take precendence over instance attributes.
Instance attributes take precedence over non-data descriptors.

> then what - Base classes..?

Checking base classes is part of checking the class. If a base class
has a data descriptor, that will likewise take precedence over the
instance attribute, which will likewise take precedence over non-data
descriptors in the base class.

> or does he hop back to look in the
> instance? How is C3 Linearization altered?

It's not.

> Additionally,
> class Foo:
>def __init__(self, name, value):
>  self.name = name
>
> cannot be done because
> x = Foo('bar', 10)
>
> x.bar will..? attribute in class takes precedence.. great, isn't that
> what we want?

I don't understand what you're asking here or what this example has to
do with descriptors.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-01 Thread Ben Finney
"Veek. M"  writes:

> Trying to make sense of this para:

At the risk of being ruse, I am trying to make sense of some paragraphs
in the messages you write here. Could you take a little more time to
write clearly, as a way of communicating in this forum?

> Is he say that Descriptors are a special case where Foo is checked 
> first, then what - Base classes..? or does he hop back to look in the 
> instance? How is C3 Linearization altered?

I really have no idea what this paragraph means. Can you please write
again assuming we don't know already what you are trying to say?

-- 
 \  “[I]t is impossible for anyone to begin to learn that which he |
  `\thinks he already knows.” —Epictetus, _Discourses_ |
_o__)  |
Ben Finney

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


Re: Namespaces are one honking great idea

2016-07-01 Thread Random832
On Fri, Jul 1, 2016, at 21:50, Kevin Conway wrote:
> I believe the namespace object you are referring to is exactly a
> class. IIRC, classes came about as a "module in a module".

No, because classes have instances. And conceptually they seem like they
*should* have instances. Just using the term "class" carries
expectations.

More to the point, what modules do that classes do not is provide a
global namespace for functions defined within them, so that variables
within them can be used (well, read - writing them requires a
declaration) by the functions without extra qualification.

> Regardless, all use cases you've listed are already satisfied by use
> of the static and class method decorators. Methods decorated with
> these do not require an instance initialization to use.

staticmethod isn't technically required to use a method through the
class (or subclasses), it simply provides the appropriate magic to allow
it to be called through instances.
-- 
https://mail.python.org/mailman/listinfo/python-list


View committed code via gitpython

2016-07-01 Thread Jason Bailey
Hi all,

I'm trying to essentially replicate "gift grep" functionality with gitpython 
and am not quite sure how to pull the committed code from the repo using 
gitpython. I am successfully listing all the commits, so now all I need to do 
is view the code in each commit to do some regex matching on it. Anyone savvy 
with this module that could steer me in the right direction???

Thanks

Jason
-- 
https://mail.python.org/mailman/listinfo/python-list


View committed code via gitpython

2016-07-01 Thread Jason Bailey
Hi all,

I'm trying to essentially replicate "gift grep" functionality with gitpython 
and am not quite sure how to pull the committed code from the repo using 
gitpython. I am successfully listing all the commits, so now all I need to do 
is view the code in each commit to do some regex matching on it. Anyone savvy 
with this module that could steer me in the right direction???

Thanks

Jason
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Ian Kelly
On Fri, Jul 1, 2016 at 4:08 PM, Lawrence D’Oliveiro
 wrote:
> On Tuesday, June 28, 2016 at 5:03:08 PM UTC+12, Ben Finney wrote:
>> There is a clever one-line decorator that has been copy-pasted without
>> explanation in many code bases for many years::
>>
>> decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda 
>> func: decorator(func, *args, **kwargs)
>>
>
> For those who want docstrings, I’ll give you docstrings:
>
> def decorator_with_args(decorator) :
> "given function decorator(func, *args, **kwargs), returns a decorator 
> which," \
> " given func, returns the result of decorator(func, *args, **kwargs)."
>
> def decorate(*args, **kwargs) :
>
> def generated_decorator(func) :
> return \
> decorator(func, *args, **kwargs)
> #end generated_decorator
>
> #begin decorate
> generated_decorator.__name__ = 
> "decorator_{}".format(decorator.__name__)
> generated_decorator.__doc__ = "decorator which applies {} to the 
> previously-specified arguments".format(decorator.__name__)
> return \
> generated_decorator
> #end decorate
>
> #begin decorator_with_args
> decorate.__name__ = "decorate_with_{}".format(decorator.__name__)
> decorate.__doc__ = "generates a decorator which applies {} to the 
> given arguments".format(decorator.__name__)

You should use functools.wraps instead of clobbering the decorated
function's name and docstring:

@functools.wraps(decorator)
def decorate(*args, **kwargs):
...

> return \
> decorate

Just to satisfy my own curiosity, do you have something against
putting the return keyword and the returned expression on the same
line?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Ben Finney
Ian Kelly  writes:

> You should use functools.wraps instead of clobbering the decorated
> function's name and docstring:
>
> @functools.wraps(decorator)
> def decorate(*args, **kwargs):
> ...

Thanks. Can you write the full implementation with that, so I can be
sure of where you expect that to go?

-- 
 \  “I knew things were changing when my Fraternity Brothers threw |
  `\   a guy out of the house for mocking me because I'm gay.” |
_o__)  —postsecret.com, 2010-01-19 |
Ben Finney

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


Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Ian Kelly
On Fri, Jul 1, 2016 at 11:32 PM, Ben Finney  wrote:
> Ian Kelly  writes:
>
>> You should use functools.wraps instead of clobbering the decorated
>> function's name and docstring:
>>
>> @functools.wraps(decorator)
>> def decorate(*args, **kwargs):
>> ...
>
> Thanks. Can you write the full implementation with that, so I can be
> sure of where you expect that to go?

def decorator_with_args(decorator):
"""Given function decorator(func, *args, **kwargs), returns a
wrapper that accepts args and kwargs separately from func.
"""
@functools.wraps(decorator)
def apply(*args, **kwargs):
# inner_decorator is transient, so its name and docstring
# are unimportant.
def inner_decorator(func):
return decorator(func, *args, **kwargs)
return inner_decorator
return apply
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Controlling the Mac OSX GUI via Python?

2016-07-01 Thread Christian Gollwitzer

Am 02.07.16 um 05:16 schrieb Lawrence D’Oliveiro:

On Friday, July 1, 2016 at 4:59:11 PM UTC+12, Christian Gollwitzer wrote:

Yes, simulating mouse clicks with
fixed coordinates etc. is prone to such failure, but there are better
methods. These mouse clicks and keyboard events usually trigger a method
call inside the GUI program. If there are any means to call that method
directly, you are independent from the graphics itself.


Even if you could get it working reliably, scripting a GUI is going to be slow.

GUIs are only designed to work at human speeds, after all.



It might be slow, but look at his request in the OP "automatically 
arranging windows, periodically refreshing applications across multiple 
desktops". A button which arranges three programs in a row could be 
useful for some users. Or an automatic reload of a status website inside 
the browser, where you can't change the website to embed autorefresh 
code. I've got a tool running which can remap special keys (ctrl, fn) to 
ordinary chars. Also sometimes a complex functionality is buried in a 
GUI. Consider a server converting MS Word files into PDF. The only 
method which reliably works is COM to drive MS Office, yes it's clumsy, 
but unless you persuade MS to release Office as a Python library you 
have no other option.


Speed is not of any concern here. If execution speed would be important, 
why use Python at all?


Christian
--
https://mail.python.org/mailman/listinfo/python-list


Re: Meta decorator with parameters, defined in explicit functions

2016-07-01 Thread Lawrence D’Oliveiro
On Saturday, July 2, 2016 at 5:10:06 PM UTC+12, Ian wrote:
> You should use functools.wraps instead of clobbering the decorated
> function's name and docstring:

Where am I doing that?
> Just to satisfy my own curiosity, do you have something against
> putting the return keyword and the returned expression on the same
> line?

Yes.
-- 
https://mail.python.org/mailman/listinfo/python-list