Spreading a class over multiple files

2016-06-05 Thread Mark Summerfield
Sometimes I want to spread a class over multiple files.

My primary use case is when I create a "Model" class to reflect an entire SQL 
database. I want a model instance to provide a single point of access to
 the database, but the database has many tables each requiring its own methods 
since they differ in their structure, purpose, validation needs, etc.

A secondary use case is when I create "MainWindow" classes in GUI programming 
and have lots of methods to reflect all the actions (e.g., menu options 
and toolbar actions, plus interaction with the main widget(s)).

To meet these needs I've devised an approach that I think is easy to use and 
understand and which doesn't use any tricky or hard to maintain code.

My question is -- are there nicer/better ways to achieve this?

Here's a summary of my approach. A fuller discussion is on my website:
https://www.qtrac.eu/pyclassmulti.html

# Lib.py
# This provides the two functions (both decorators) used to support my approach
def add_methods_from(*modules):
def decorator(Class):
for module in modules:
for method in getattr(module, "__methods__"):
setattr(Class, method.__name__, method)
return Class
return decorator

def register_method(methods): # A decorator used purely for its side-effect
def register_method(method):
methods.append(method)
return method # Unchanged and not strictly necessary
return register_method

# Model.py
# This provides my model but some methods are in separate files
import Lib
import _ModelConfig
import _ModelOutput

@Lib.add_methods_from(_ModelConfig, _ModelOutput)
class Model:
...
def small_method(self):
...

# _ModelConfig.py # _ModelOutput has the same structure so not shown
import Lib

__methods__ = [] # self is a Model
register_method = Lib.register_method(__methods__)

@register_method
def config(self):
...
So, that's the overall pattern of my solution.

Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., 
import _ModelConfig), without resorting to stack frame hacks or similar?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Spreading a class over multiple files

2016-06-05 Thread Gary Herron

On 06/04/2016 11:55 PM, Mark Summerfield wrote:

Sometimes I want to spread a class over multiple files.


There’s and easy way to do this in Python using what's called a Mixin 
class and (multiple) inheritance:

  (See https://en.wikipedia.org/wiki/Mixin for more information.)

In one file, say extras.py

   class ExtraMethodsMixin:

  def extra_1(...):
  ...

  def extra_2(...):
  ...



In the main class file:

   from extras import ExtraMethodsMixin

   class MainClass(ExtraMethodsMixin):

  def __init__(...):
  ...
   # and so on


The result will be essentially the same as if all three methods were 
defined in MainCLass.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418





My primary use case is when I create a "Model" class to reflect an entire SQL 
database. I want a model instance to provide a single point of access to
  the database, but the database has many tables each requiring its own methods 
since they differ in their structure, purpose, validation needs, etc.

A secondary use case is when I create "MainWindow" classes in GUI programming 
and have lots of methods to reflect all the actions (e.g., menu options
and toolbar actions, plus interaction with the main widget(s)).

To meet these needs I've devised an approach that I think is easy to use and 
understand and which doesn't use any tricky or hard to maintain code.

My question is -- are there nicer/better ways to achieve this?

Here's a summary of my approach. A fuller discussion is on my website:
https://www.qtrac.eu/pyclassmulti.html

# Lib.py
# This provides the two functions (both decorators) used to support my approach
def add_methods_from(*modules):
 def decorator(Class):
 for module in modules:
 for method in getattr(module, "__methods__"):
 setattr(Class, method.__name__, method)
 return Class
 return decorator

def register_method(methods): # A decorator used purely for its side-effect
 def register_method(method):
 methods.append(method)
 return method # Unchanged and not strictly necessary
 return register_method

# Model.py
# This provides my model but some methods are in separate files
import Lib
import _ModelConfig
import _ModelOutput

@Lib.add_methods_from(_ModelConfig, _ModelOutput)
class Model:
 ...
 def small_method(self):
 ...

# _ModelConfig.py # _ModelOutput has the same structure so not shown
import Lib

__methods__ = [] # self is a Model
register_method = Lib.register_method(__methods__)

@register_method
def config(self):
 ...
So, that's the overall pattern of my solution.

Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., 
import _ModelConfig), without resorting to stack frame hacks or similar?


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


Re: Lineendings (was Everything good about Python except GUI IDE?)

2016-06-05 Thread Rustom Mody
Just came across this new data (for me) to this old question:

On Monday, February 29, 2016 at 8:05:33 AM UTC+5:30, Ben Finney wrote:
> Rustom Mody writes:
> 
> > On Monday, February 29, 2016 at 7:33:18 AM UTC+5:30, Chris Angelico wrote:
> > > Never has for any of my projects. Examples please? Actual real
> > > problems? I've been using git for years, on mixed platforms for a lot
> > > of that, and not had a single problem.
> >
> > Pragmatically: As I said just search stackoverflow for git:crlf
> 
> Don't ask Chris to *guess* which search results are representative of
> what you're asserting. Please provide concrete examples that demonstrate
> specifically what you're describing.

A graphic description of the problem:
http://www.hanselman.com/blog/YoureJustAnotherCarriageReturnLineFeedInTheWall.aspx

Along with a solution that is not universally working
https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread Peter Otten
ICT Ezy wrote:

 2 ** 3 ** 2
> Answer is 512
> Why not 64?
> Order is right-left or left-right?

** is a special case:

"""
The power operator ** binds less tightly than an arithmetic or bitwise unary 
operator on its right, that is, 2**-1 is 0.5.
"""
https://docs.python.org/3.5/reference/expressions.html#id21

Here's a little demo:

$ cat arithdemo.py
class A:
def __init__(self, value):
self.value = str(value)
def __add__(self, other):
return self._op(other, "+")
def __pow__(self, other):
return self._op(other, "**")
def __repr__(self):
return self.value
def _op(self, other, op):
return A("({} {} {})".format(self.value, op, other.value))
$ python3 -i arithdemo.py 
>>> A(1) + A(2) + A(3)
((1 + 2) + 3)
>>> A(1) ** A(2) ** A(3)
(1 ** (2 ** 3))


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


Re: Spreading a class over multiple files

2016-06-05 Thread Peter Otten
Mark Summerfield wrote:

> Sometimes I want to spread a class over multiple files.
> 
> My primary use case is when I create a "Model" class to reflect an entire
> SQL database. I want a model instance to provide a single point of access
> to
>  the database, but the database has many tables each requiring its own
>  methods since they differ in their structure, purpose, validation needs,
>  etc.

In other words, a God Class

http://c2.com/cgi/wiki?GodClass

> My question is -- are there nicer/better ways to achieve this?

Use composition.

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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Marko Rauhamaa
Steven D'Aprano :

> On Sun, 5 Jun 2016 01:17 pm, Lawrence D’Oliveiro wrote:
>> Are variables like little boxes? Yes they are. 
>
> That's *exactly* what variables in Python are not like.

Of course they are.

Or, rather, the little-box mental model is no worse than any other.

You could also think of variables as pegs, references as leashes, and
objects as cute puppies. One puppy could be held with multiple leashes
hung on separate pegs. Some puppies hold leashes in their mouths. Every
leash is tied to a puppy or a special wooden post called None.

>> But they are all the same size, while objects may be large (even very
>> large) or small. That is why variables hold, not objects, but
>> references to objects.
>
> No they don't. You are confusing the implementation with the
> programming model.

The easiest way to understand the references of Java, Python, Lisp and
others is through an underlying implementation. I really haven't seen a
better abstract model presented.

(An alternate model could be the semantics of lambda calculus, which
doesn't have a data model at all! Instead, the semantics are given
through the execution model: a form is repeatedly transformed to new
forms until no transformation is allowed by the rules. That kind of
model would not suit Python, though, because Python's little boxes can
be assigned to.)

> Following the assignment:
>
> x = 99
>
> if you print(x), do you see something like "reference 0x12345"? No.

Irrelevant. The statement "print(x)" does not print a variable but the
result of the evaluation of the given expression.

> There is no analog to dereferencing in Python, nothing like print(x^).

True, variables are not first-class objects in Python.

(However, Guido could add first-class status to variables to Python with
the snap of his fingers in a 100%-backwards-compatible manner.)

> You bind values (that is, objects) directly to names, and names
> (variables) hold their value, not a reference to their value.

That mental model seems more confusing than the little-box one.

> The fact that for some implementations that is implemented using
> references of some sort or another (e.g. pointers in CPython) is an
> implementation detail which is irrelevant to the language and its
> execution model.

The references cannot be removed from Python's data model. In fact, they
haven't been:

   The value of an immutable container object that contains a REFERENCE
   to a mutable object can change when the latter’s value is changed;

   [...]

   Some objects contain REFERENCES to other objects; these are called
   containers. Examples of containers are tuples, lists and
   dictionaries. The REFERENCES are part of a container’s value. In most
   cases, when we talk about the value of a container, we imply the
   values, not the identities of the contained objects; however, when we
   talk about the mutability of a container, only the identities of the
   immediately contained objects are implied. So, if an immutable
   container (like a tuple) contains a REFERENCE to a mutable object,
   its value changes if that mutable object is changed.

   Types affect almost all aspects of object behavior. Even the
   importance of object identity is affected in some sense: for
   immutable types, operations that compute new values may actually
   return a REFERENCE to any existing object with the same type and
   value, while for mutable objects this is not allowed. E.g., after a =
   1; b = 1, a and b may or may not REFER to the same object with the
   value one, depending on the implementation, but after c = []; d = [],
   c and d are guaranteed to REFER to two different, unique, newly
   created empty lists. (Note that c = d = [] assigns the same object to
   both c and d.)

   [etc etc]

   https://docs.python.org/3/reference/datamodel.html>
   (capitalization is mine)


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


Re: Spreading a class over multiple files

2016-06-05 Thread Mark Summerfield
You're quite right! For some reason I have a blind-spot about mixins, but they 
are the perfect solution. Thanks:-)
-- 
https://mail.python.org/mailman/listinfo/python-list


EuroPython 2016: Hot Topics Call for Proposals is Open !

2016-06-05 Thread M.-A. Lemburg
We are happy to announce that we’ve opened our second Call for
Proposals. This call is limited to hot topics and most recent
developments in software and technology and will run until June 12.


   *** Proposal Submission Page ***

   https://ep2016.europython.eu/en/speakers/hot-topics-cfp/


Why is there a second call ?


Planning a big conference is a challenge: On one hand people like to
know what will be on our talk schedule to make up their mind and make
travel arrangements early. On the other hand technology is progressing
at enormous speed these days.

So we have given this some thought and decided to split the Call for
Proposals in two phases, with the second just weeks before the
conference.


Submit your hot topic talk
--

This CFP is reserved for:

 * hot topics
 * emerging technologies
 * brand new developments in software & hardware
 * recent results in research and science

Some suggestions for topics:

 * Exciting new hardware & Internet of Things
 * Robotics
 * Virtual Reality
 * AI & Deep Learning

The second call will be open for nine days only:

Saturday June 4th 0:00 to Sunday June 12th 24:00 CEST.

The program work group will then select the most exciting and
intriguing submissions and will notify the winners on short notice.


Submit your poster or run a help desk
-

Since we still have a few slots left, we are also looking for more
posters and help desks - these are not limited to hot topics.


Get a ticket discount
-

For talks, posters, help desks we will give out a 25% discount coupon
valid for one conference ticket.


With gravitational regards,
--
EuroPython 2016 Team
http://ep2016.europython.eu/
http://www.europython-society.org/


PS: Please forward or retweet to help us reach all interested parties:
https://twitter.com/europython/status/739409571031187456
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Taking two and more data frames and extracting data on unique keys in python

2016-06-05 Thread Danish Hussain

1
down vote
favorite
Its a bit long question have patience. firstly I have 2 data frames one in 
which i have name of a guy and pages liked by him in columns. So no. of columns 
will be different for different person here is the example. 1st column is the 
name of user.Then pages liked by him is stored across the row.So no. of columns 
for 'random guy' will be different from 'mank rion'. 'BlackBick' , '500 
Startups' e.t.c are name of the page. let say name of this data frame is 
User_page

random guy  BlackBuckGiveMeSportAnalytics Ninja 
mank nion   DJ CHETASCelina Jaitly  Gurkeerat Singh
pop rajuel  WOW Editions 500 Startups   Biswapati Sarkar
Roshan ghai MensXP   No Abuse   the smartian 
Now I have another Data frame in which is kind of same as upper one but in the 
place of page's name there is a category of page.you might now there are 
different category of pages on fb. so let say 'BlacBuck''s category is 
'Transport/Freight'. There are pages with same name and different category.That 
is why i cant use name directly as key this is how my data frame looks like.Let 
say name of this data frame User_category.

random guy  Transport/FreightSport  Insurance Company 
mank nion   Arts/Entertainment   ActressActor/Director
pop rajuel  Concert Tour App Page   Actor/Director
Roshan ghai News/Media Website   Community  Public Figure  
Now I have two more Data frames. one in which I have name of fb pages as 1st 
column and 162 more columns with some tag for each page there is value 1 for 
i*j element if ith page comes in to jth tag otherwise left empty so it will 
look like.let say name of this dataframe is Page_tag

name of page  tag 1tag2tag3
BlackBuck 1  1 
GiveMeSport   1  1
Analytics Ninja   1  1
DJ CHETAS1   1
the another one have name of categories as 1st column and same 162 as further. 
like this. let say name of this dataframe is Category_tag.

   category_name  tag 1tag2tag3
Sport 1   1
App Page  1   1
Actor/Director1
Public Figure 1   1
Now what I have to get the tag counts for each user from pages he has liked. 
for that first I have to first check that the page which he has liked where 
exist in data frame of Page_tag which is 3rd dataframe in my question if it 
exist there take the counts of tags that how many times a specific tags 
appeared for that user.this is first step if not found the name of page as no. 
of pages in Page_tag dataframe(3rd one) is limited. I will go to category of 
page (from 2nd dataframe in this question) for the pages which are left out and 
for that category i will count the tags count for the specific user from 
dataframe named Category_tags(4th dataframe in this question) and sum the tag 
count and my output something like this. Output

username tag1   tag2   tag3 
random guy  1  2 2 
mank nion   2  1 3
pop rajuel  4  0 2 
Roshan ghai 0  2 1
a i*j element on this dataframe shows no. times that the jth tag appears for 
ith user. I have written code for this and more in R i am stuck in this 
particular step. The code of R wasnt optimal as i used loops many time. I 
wanted to rhis optimally, hopefully can be done in pandas. Please me know if 
clarification is needed. Any help will be appreciated. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Spreading a class over multiple files

2016-06-05 Thread Steven D'Aprano
On Sun, 5 Jun 2016 06:14 pm, Mark Summerfield wrote:

> You're quite right! For some reason I have a blind-spot about mixins, but
> they are the perfect solution. Thanks:-)

They really aren't :-)

Just yesterday on an unrelated thread I linked to a long discussion about
multiple inheritance, mixins and traits. See links here:

https://mail.python.org/pipermail/python-list/2016-June/709808.html

To my mind, if you have to split a class over multiple files, it probably
does too much. The "God Class" that Peter referred to is an anti-pattern:

https://en.wikipedia.org/wiki/God_object

but if you still need to split your class over multiple files, this is how I
would do it:


# file a.py
class Zeus_King_Of_The_Gods:  # *wink*

from b import throw_lightening
from c import turn_into_a_shower_of_gold

def turn_into_animal(self, animal='bull'):
...


# file b.py
def throw_lightening(self):
...


# file c.py
def turn_into_a_shower_of_gold(self):
...



Notice that in files b and c you define the functions with an explicit self,
even though they are at the top level.



-- 
Steven

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


Re: for / while else doesn't make sense

2016-06-05 Thread Ned Batchelder
On Saturday, June 4, 2016 at 11:29:30 PM UTC-4, Lawrence D’Oliveiro wrote:
> On Saturday, June 4, 2016 at 11:37:18 PM UTC+12, Ned Batchelder wrote:
> > On Friday, June 3, 2016 at 11:43:33 PM UTC-4, Lawrence D’Oliveiro wrote:
> > > On Saturday, June 4, 2016 at 3:00:36 PM UTC+12, Steven D'Aprano wrote:
> > > > You can exit a loop because you have run out of items to process, or 
> > > > you can
> > > > exit the loop because a certain condition has been met.
> > > 
> > > But why should they be expressed differently?
> > > 
> > > item_iter = iter(items)
> > > while True :
> > > item = next(item_iter, None)
> > > if item == None :
> > > break
> > > if is_what_i_want(item) :
> > > break
> > > #end while
> > 
> > Do you actually write loops like this?
> 
> Is that a non-trolling question? Yes. All the time.

OK. The best I can say is that you seem to think very differently about
your code than I do.  Re-implementing the logic of iteration just so you
can make the two end conditions look similar seems like a very bad
trade-off to me.  It adds more lines, and more names, and as Steven
points out, more opportunities to introduce errors.

> When a language has good and bad parts, it behooves the wise programmer to 
> concentrate on the good parts and try to ignore the bad.
> 
> Python’s for-loops have their uses—I *did* point this out too, did you not 
> notice?—but they are best confined to the situations that they are good at.

I'm not sure what part of Python you are putting in the "bad" category.
This example didn't involve for/else, so are you saying that break statements
inside for-loops are a bad part?

IIRC, this started as a comparison of Python's for loops and C's.  Do you
also write C for-loops as while statements if they have a break in them,
to make both of those end conditions similar?

I'm not trolling, I'm trying to understand your unusual approach.

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


Re: for / while else doesn't make sense

2016-06-05 Thread Marko Rauhamaa
Ned Batchelder :

> On Saturday, June 4, 2016 at 11:29:30 PM UTC-4, Lawrence D’Oliveiro wrote:
>> > > item_iter = iter(items)
>> > > while True :
>> > > item = next(item_iter, None)
>> > > if item == None :
>> > > break
>> > > if is_what_i_want(item) :
>> > > break
>> > > #end while
>
> OK. The best I can say is that you seem to think very differently
> about your code than I do. Re-implementing the logic of iteration just
> so you can make the two end conditions look similar seems like a very
> bad trade-off to me. It adds more lines, and more names, and as Steven
> points out, more opportunities to introduce errors.

I often experiment with different loop constructs to find the one most
pleasing to the eye. Working directly off iterators is quite rare but a
while-vs-for consideration is frequent. Also, should the stepping part
be in the beginning, middle or end of the loop body?

> I'm not sure what part of Python you are putting in the "bad"
> category. This example didn't involve for/else, so are you saying that
> break statements inside for-loops are a bad part?

It takes time to acclimatize to a new programming language. Initially,
you tend to shun odd-looking constructs like comprehensions. Then, you
might overdo constructs like lambdas and maps. Eventually, you'll find a
style the suits both you and the language.


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


Re: Anyone know a donation app codebase?

2016-06-05 Thread Albert
Thank you for your answer Ben,

That is not exactly what I am looking for. I am interested in knowing if there 
are any python (django, flask, etc) opensource projects for managing donations, 
similar to catarse [1] (ruby) and [2] (ruby).

[1]: https://github.com/catarse/catarse
[2]: https://github.com/danielweinmann/unlock

Any suggestion please?

On Saturday, June 4, 2016 at 6:02:51 PM UTC-3, Ben Finney wrote:
> Albert writes:
> 
> > Anyone knows a donation app whose code is available on github or
> > similar made in python (could be django, flask, or any other web
> > framework).
> 
> Search for Python libraries on the Python Package Index
> https://pypi.python.org/>.
> 
> What you are (I think) looking for can be called a “payment” handler
> https://pypi.python.org/pypi?%3Aaction=search&term=payment&submit=search>.
> If that's not right you can try different search terms.
> 
> -- 
>  \ “My, your, his, hers, ours, theirs, its. I'm, you're, he's, |
>   `\   she's, we're, they're, it's.” —anonymous, alt.sysadmin.recovery |
> _o__)  |
> Ben Finney

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


Re: Lineendings (was Everything good about Python except GUI IDE?)

2016-06-05 Thread MRAB

On 2016-06-05 08:34, Rustom Mody wrote:

Just came across this new data (for me) to this old question:

On Monday, February 29, 2016 at 8:05:33 AM UTC+5:30, Ben Finney wrote:

Rustom Mody writes:

> On Monday, February 29, 2016 at 7:33:18 AM UTC+5:30, Chris Angelico wrote:
> > Never has for any of my projects. Examples please? Actual real
> > problems? I've been using git for years, on mixed platforms for a lot
> > of that, and not had a single problem.
>
> Pragmatically: As I said just search stackoverflow for git:crlf

Don't ask Chris to *guess* which search results are representative of
what you're asserting. Please provide concrete examples that demonstrate
specifically what you're describing.


A graphic description of the problem:
http://www.hanselman.com/blog/YoureJustAnotherCarriageReturnLineFeedInTheWall.aspx

Along with a solution that is not universally working
https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372

Years ago, I was making PPD (PostScript Printer Description) files for 
Mac and PC. The spec. stated that the line endings could be CR, LF or CR+LF.


All went well until one day someone reported that they wouldn't install 
on a Mac, which they had done previously.


It turned out that the Mac had a newer version of MacOS, which now 
insisted that the line endings be CR only...

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


Re: Operator precedence problem

2016-06-05 Thread ICT Ezy
On Sunday, June 5, 2016 at 1:06:21 PM UTC+5:30, Peter Otten wrote:
> ICT Ezy wrote:
> 
>  2 ** 3 ** 2
> > Answer is 512
> > Why not 64?
> > Order is right-left or left-right?
> 
> ** is a special case:
> 
> """
> The power operator ** binds less tightly than an arithmetic or bitwise unary 
> operator on its right, that is, 2**-1 is 0.5.
> """
> https://docs.python.org/3.5/reference/expressions.html#id21
> 
> Here's a little demo:
> 
> $ cat arithdemo.py
> class A:
> def __init__(self, value):
> self.value = str(value)
> def __add__(self, other):
> return self._op(other, "+")
> def __pow__(self, other):
> return self._op(other, "**")
> def __repr__(self):
> return self.value
> def _op(self, other, op):
> return A("({} {} {})".format(self.value, op, other.value))
> $ python3 -i arithdemo.py 
> >>> A(1) + A(2) + A(3)
> ((1 + 2) + 3)
> >>> A(1) ** A(2) ** A(3)
> (1 ** (2 ** 3))

Thank you very much for your explanation 
-- 
https://mail.python.org/mailman/listinfo/python-list


how to work await x operator?

2016-06-05 Thread ICT Ezy
how to work await x Await expression operator? 
pl explain any one ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to work await x operator?

2016-06-05 Thread Marko Rauhamaa
ICT Ezy :

> how to work await x Await expression operator? 
> pl explain any one ...

A coroutine can't be called directly. A call to a coroutine must be
prefixed with the "async" keyword. That allows Python to perform a
context switch between coroutines in case the coroutine needs to wait
for the operation to complete.


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


Re: Operator precedence problem

2016-06-05 Thread Uri Even-Chen
My suggestion: Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
+ 5, without parentheses. Always add parentheses - 2 ** (3 ** 2) (or (2 **
3) **2) or (2 * 4) + 5 (or 2 * (4 + 5)).


*Uri Even-Chen*
[image: photo] Phone: +972-54-3995700
Email: u...@speedy.net
Website: http://www.speedysoftware.com/uri/en/
  
    

On Sun, Jun 5, 2016 at 6:05 PM, ICT Ezy  wrote:

> On Sunday, June 5, 2016 at 1:06:21 PM UTC+5:30, Peter Otten wrote:
> > ICT Ezy wrote:
> >
> >  2 ** 3 ** 2
> > > Answer is 512
> > > Why not 64?
> > > Order is right-left or left-right?
> >
> > ** is a special case:
> >
> > """
> > The power operator ** binds less tightly than an arithmetic or bitwise
> unary
> > operator on its right, that is, 2**-1 is 0.5.
> > """
> > https://docs.python.org/3.5/reference/expressions.html#id21
> >
> > Here's a little demo:
> >
> > $ cat arithdemo.py
> > class A:
> > def __init__(self, value):
> > self.value = str(value)
> > def __add__(self, other):
> > return self._op(other, "+")
> > def __pow__(self, other):
> > return self._op(other, "**")
> > def __repr__(self):
> > return self.value
> > def _op(self, other, op):
> > return A("({} {} {})".format(self.value, op, other.value))
> > $ python3 -i arithdemo.py
> > >>> A(1) + A(2) + A(3)
> > ((1 + 2) + 3)
> > >>> A(1) ** A(2) ** A(3)
> > (1 ** (2 ** 3))
>
> Thank you very much for your explanation
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread Chris Angelico
On Sun, Jun 5, 2016 at 4:53 PM, ICT Ezy  wrote:
 2 ** 3 ** 2
> Answer is 512
> Why not 64?
> Order is right-left or left-right?

This example follows the mathematical standard; you start from the
"top" (the right hand side), and work your way down.

>>> (3**3) % 10
7
>>> (3**3**3) % 10
7
>>> (3**3**3**3) % 10
 waiting..

https://en.wikipedia.org/wiki/Graham%27s_number

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


Re: Operator precedence problem

2016-06-05 Thread Random832
On Sun, Jun 5, 2016, at 02:53, ICT Ezy wrote:
> >>> 2 ** 3 ** 2 
> Answer is 512
> Why not 64?
> Order is right-left or left-right?

You're mixing up order of evaluation with operator associativity. The **
operator is right-to-left associative, this means x ** y ** z == x ** (y
** z). Evaluation is left to right, where it matters [i.e. if one or
more of the elements here were an expression with side effects]: first x
is evaluated, then tmp=y**z, then x**tmp. These are two entirely
different concepts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Random832
On Sun, Jun 5, 2016, at 02:37, Steven D'Aprano wrote:
> No they don't. You are confusing the implementation with the programming
> model.
> 
> Following the assignment:
> 
> x = 99
> 
> if you print(x), do you see something like "reference 0x12345"? No.
> 
> Do you have to dereference that reference to get the value of x? No.
>
> At the Python level, the value of x is 99, not some invisible,
> untouchable reference to 99.

Sure, but that is the value of the object referenced by x, it is not a
property of x itself.

x = y = 999; z = int('999')
x is y # True
x is z # False

How would you describe the difference between x and y, and z? This is
not a mere implementation detail [though, the fact that for int in
particular I had to go higher than 99 to get this result is - I wouldn't
have had this problem with strings, and I *couldn't* have had this
problem with lists]. The fact that two objects can have the same value
while being different objects, and that two variables can point to the
same object, are part of the programming model. Immutable objects do
tend to blur the line, since implementations are permitted to make them
the same even when they're apparently independent.

The fact that == is an operator distinct from 'is' inherently means that
variables contain references, not objects.

There is, obviously, only one value in my example. If variables
contained objects, then my example would have three objects, none more
or less distinct. They contain references, and that is the only way
there are two objects, and that is the only model in which there are two
of anything.

[but, hey, at least we can agree that Python has variables.]

> There is no analog to dereferencing in Python, nothing like print(x^).

I don't see where anyone said there was. I think you've inferred meaning
to the statement "python variables contain references" that it does not
actually have.

> You bind values (that is, objects)

Values are not objects. x and z have the same value, and their objects
are identical but distinct, but they are different because they point
(or refer, or by your weird terminology "bind") to different objects.

> directly to names, and names (variables) hold their value, not a
> reference to their value.

They hold a reference to an object. The object holds the value.

> The fact that for some implementations that is implemented using
> references of some sort or another (e.g. pointers in CPython) is an
> implementation detail which is irrelevant to the language and its
> execution model.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Random832
On Sun, Jun 5, 2016, at 04:01, Marko Rauhamaa wrote:
> You could also think of variables as pegs, references as leashes, and
> objects as cute puppies. One puppy could be held with multiple leashes
> hung on separate pegs. Some puppies hold leashes in their mouths. Every
> leash is tied to a puppy or a special wooden post called None.

You've got it all wrong about what's special about None.  The object is
just another puppy. There *is* a variable called None
[getattr(__builtins__, 'None')] which holds a leash tied to that puppy,
but it's rarely used, since everyone knows how to find that puppy
directly [None is a keyword]. But nothing's special about the object
itself, no more than any other object.

Of course, as the fact that I had to use __builtins__ shows, the "pegs"
are a fiction. At least, as long as we consider that frames and modules
are just another kind of puppy. Though I suppose technically frames are
an implementation detail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Spreading a class over multiple files

2016-06-05 Thread Terry Reedy

On 6/5/2016 2:55 AM, Mark Summerfield wrote:

Sometimes I want to spread a class over multiple files.


My experience with trying to work with two do-all classes in idlelib has 
engendered a dislike for such.  It is hard to find things in a 
kitchen-sink class.  To switch IDLE from being a multi-window 
application to having multiple panes in a single window, both must be 
refactored.



My primary use case is when I create a "Model" class to reflect an
entire SQL database. I want a model instance to provide a single
point of access to the database, but the database has many tables
each requiring its own methods since they differ in their structure,
purpose, validation needs, etc.


I would consider a master database ('Model') class, a base table class, 
and a subclass class for each table or group of similar tables.



A secondary use case is when I create "MainWindow" classes in GUI
programming and have lots of methods to reflect all the actions
(e.g., menu options and toolbar actions, plus interaction with the
main widget(s)).


With tk and tkinter, at least, implementation functions do not have to 
be in the same file as the menu or toolbar definitions.


--
Terry Jan Reedy

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


Re: Anyone know a donation app codebase?

2016-06-05 Thread Ben Finney
Albert  writes:

> Thank you for your answer Ben,

You're welcome. Please note that top-posting is poor etiquette for
discussions; instead, interleave your response like a written dialogue.
See https://en.wikipedia.org/wiki/Posting_style#Interleaved_style>.

> That is not exactly what I am looking for. I am interested in knowing
> if there are any python (django, flask, etc) opensource projects for
> managing donations

Again, PyPI is the place to search
https://pypi.python.org/pypi?:action=search&term=django%20donation&submit=search>.

> Any suggestion please?

I hope that helps.

-- 
 \  “It seems intuitively obvious to me, which means that it might |
  `\   be wrong.” —Chris Torek |
_o__)  |
Ben Finney

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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Marko Rauhamaa
Random832 :

> On Sun, Jun 5, 2016, at 04:01, Marko Rauhamaa wrote:
>> You could also think of variables as pegs, references as leashes, and
>> objects as cute puppies. One puppy could be held with multiple
>> leashes hung on separate pegs. Some puppies hold leashes in their
>> mouths. Every leash is tied to a puppy or a special wooden post
>> called None.
>
> You've got it all wrong about what's special about None. The object is
> just another puppy. There *is* a variable called None
> [getattr(__builtins__, 'None')] which holds a leash tied to that
> puppy, but it's rarely used, since everyone knows how to find that
> puppy directly [None is a keyword]. But nothing's special about the
> object itself, no more than any other object.

I say None is a wooden post, you say None is a puppy.

What piece of Python code could put our dispute to rest?


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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Marko Rauhamaa
Random832 :

> On Sun, Jun 5, 2016, at 02:37, Steven D'Aprano wrote:
>> You bind values (that is, objects)
>
> Values are not objects. x and z have the same value, and their objects
> are identical but distinct, but they are different because they point
> (or refer, or by your weird terminology "bind") to different objects.

Terminological disputes are not very useful. However, note that your
use of the word "value" is not the only one:

   Assignment statements are used to (re)bind names to values and to
   modify attributes or items of mutable objects
   https://docs.python.org/3/reference/simple_stmts.h
   tml#assignment-statements>

   The returned value (if any) is used as an argument to construct
   StopIteration and becomes the StopIteration.value attribute.
   https://docs.python.org/3/reference/simple_stmts.h
   tml#the-return-statement>

   The type of the exception is the exception instance’s class, the
   value is the instance itself.
   https://docs.python.org/3/reference/simple_stmts.htm
   l#the-raise-statement>

while on the other hand,

   Every object has an identity, a type and a value.
   https://docs.python.org/3/reference/datamodel.htm
   l#objects-values-and-types>

   The operators <, >, ==, >=, <=, and != compare the values of two
   objects. The objects do not need to have the same type.
   https://docs.python.org/3/reference/expressions.htm
   l#value-comparisons>

IOW, sometimes the word "value" is a synonym of "object," at other times
it refers to the specific characteristics of an object. The latter
concept is not defined very clearly:

   The value of some objects can change. Objects whose value can change
   are said to be mutable; objects whose value is unchangeable once they
   are created are called immutable. (The value of an immutable
   container object that contains a reference to a mutable object can
   change when the latter’s value is changed; however the container is
   still considered immutable, because the collection of objects it
   contains cannot be changed. So, immutability is not strictly the same
   as having an unchangeable value, it is more subtle.) An object’s
   mutability is determined by its type; for instance, numbers, strings
   and tuples are immutable, while dictionaries and lists are mutable.
   https://docs.python.org/3/reference/datamodel.html#objec
   ts-values-and-types>


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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Random832
On Sun, Jun 5, 2016, at 15:20, Marko Rauhamaa wrote:
> I say None is a wooden post, you say None is a puppy.
> 
> What piece of Python code could put our dispute to rest?

isinstance(None, object)

Anyway, I read the "wooden post" claim as suggesting that a reference to
None is somehow different from other references, as null in C# or Java
is different from an object reference in those languages.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread cs

On 03Jun2016 16:09, Sayth Renshaw  wrote:

(By the way, the "pf = pf.append(thing)" construction is weird.
All you need is pf.append(thing).)


I got the pf = pf.append(thing) from doing pandas because in pandas its not an 
inplace function.


In Python this doesn't do what you think. The convention with most Python 
methods is that methods which perform an in-place action return None, which 
means the above assignment will unbind "pf", binding it to None instead.


BTW, the short answer to why you can't just say pf.append(thing) and have "pf" 
be a list is that ".append" is not _inherently_ a list method i.e. the langauge 
does not specify that name as special. You can have another type where .append 
does somehing else. Therefore, the deduction that pf is uspposed to be a list 
may not be made.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread Michael Torrie
On 06/05/2016 10:05 AM, Uri Even-Chen wrote:
> My suggestion: Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
> + 5, without parentheses. Always add parentheses - 2 ** (3 ** 2) (or (2 **
> 3) **2) or (2 * 4) + 5 (or 2 * (4 + 5)).

I can understand using parenthesis when operator precedence isn't
working the way you want or expect, but I certainly would not recommend
using it for basic arithmetic with multiplication, division, addition
and subtraction. The rules of precedence for multiplication and division
are well known and well-understood. If a language failed to implement
them that would be a bug.  I think for the simple things extraneous
parenthesis makes expressions more difficult for a human to parse
because he will tend to second guess himself owing to extra parens.

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


Re: Yet Another Cairo API Binding

2016-06-05 Thread Lawrence D’Oliveiro
On Thursday, June 2, 2016 at 9:16:25 AM UTC+12, I wrote:
> Thought I would mention Qahirah , which is
> yet another binding for the Cairo  graphics
> library.

To add to this, I have bindings for Pixman 
 (examples at 
) and FreeType 
 (examples at 
).

Of course, everybody wants to see pretty pictures. So have a look here 
, here 
 
and here 
.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Gregory Ewing

Random832 wrote:

There *is* a variable called None
[getattr(__builtins__, 'None')] which holds a leash tied to that puppy
... But nothing's special about the object
itself, no more than any other object.


The only special-ish thing about it is that it's unique --
there will never be another one like it, no matter how
much dog breeding you do. Fortunately, it's also immortal.

It's not the only puppy with that property, though.
For instance, there's the pair True and False, born
of the same litter but of quite opposite temperaments.
And type, the ancient mother of all canines.

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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Lawrence D’Oliveiro
On Sunday, June 5, 2016 at 3:18:05 PM UTC+12, I wrote:

> (This makes no difference for immutable objects, only mutable ones.)

I retract this part.

Thanks, Marko, for showing me where I was wrong. :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Lawrence D’Oliveiro
On Monday, June 6, 2016 at 1:08:21 PM UTC+12, Gregory Ewing wrote:
> The only special-ish thing about [None] is that it's unique --
> there will never be another one like it, no matter how
> much dog breeding you do. Fortunately, it's also immortal.

Maybe not immortal, but it seems to have 533 lives.

Anybody who writes a C extension module for Python knows that Py_None is an 
object just like any other, and has to be treated the same in terms of managing 
its reference counts.

(That’s how many unbalanced calls I had to make to Py_DECREF(Py_None) before it 
crashed Python.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread ICT Ezy
On Monday, June 6, 2016 at 5:18:21 AM UTC+5:30, Michael Torrie wrote:
> On 06/05/2016 10:05 AM, Uri Even-Chen wrote:
> > My suggestion: Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
> > + 5, without parentheses. Always add parentheses - 2 ** (3 ** 2) (or (2 **
> > 3) **2) or (2 * 4) + 5 (or 2 * (4 + 5)).
> 
> I can understand using parenthesis when operator precedence isn't
> working the way you want or expect, but I certainly would not recommend
> using it for basic arithmetic with multiplication, division, addition
> and subtraction. The rules of precedence for multiplication and division
> are well known and well-understood. If a language failed to implement
> them that would be a bug.  I think for the simple things extraneous
> parenthesis makes expressions more difficult for a human to parse
> because he will tend to second guess himself owing to extra parens.

Thank you very much for your explanation
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread ICT Ezy
On Sunday, June 5, 2016 at 9:36:20 PM UTC+5:30, Uri Even-Chen wrote:
> My suggestion: Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
> + 5, without parentheses. Always add parentheses - 2 ** (3 ** 2) (or (2 **
> 3) **2) or (2 * 4) + 5 (or 2 * (4 + 5)).
> 
> 
> *Uri Even-Chen*
> [image: photo] Phone: +972-54-3995700
> Email: u...@speedy.net
> Website: http://www.speedysoftware.com/uri/en/
>   
>     
> 
> On Sun, Jun 5, 2016 at 6:05 PM, ICT Ezy  wrote:
> 
> > On Sunday, June 5, 2016 at 1:06:21 PM UTC+5:30, Peter Otten wrote:
> > > ICT Ezy wrote:
> > >
> > >  2 ** 3 ** 2
> > > > Answer is 512
> > > > Why not 64?
> > > > Order is right-left or left-right?
> > >
> > > ** is a special case:
> > >
> > > """
> > > The power operator ** binds less tightly than an arithmetic or bitwise
> > unary
> > > operator on its right, that is, 2**-1 is 0.5.
> > > """
> > > https://docs.python.org/3.5/reference/expressions.html#id21
> > >
> > > Here's a little demo:
> > >
> > > $ cat arithdemo.py
> > > class A:
> > > def __init__(self, value):
> > > self.value = str(value)
> > > def __add__(self, other):
> > > return self._op(other, "+")
> > > def __pow__(self, other):
> > > return self._op(other, "**")
> > > def __repr__(self):
> > > return self.value
> > > def _op(self, other, op):
> > > return A("({} {} {})".format(self.value, op, other.value))
> > > $ python3 -i arithdemo.py
> > > >>> A(1) + A(2) + A(3)
> > > ((1 + 2) + 3)
> > > >>> A(1) ** A(2) ** A(3)
> > > (1 ** (2 ** 3))
> >
> > Thank you very much for your explanation
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >

Thank you very much for your explanation
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread ICT Ezy
On Sunday, June 5, 2016 at 10:49:49 PM UTC+5:30, Random832 wrote:
> On Sun, Jun 5, 2016, at 02:53, ICT Ezy wrote:
> > >>> 2 ** 3 ** 2 
> > Answer is 512
> > Why not 64?
> > Order is right-left or left-right?
> 
> You're mixing up order of evaluation with operator associativity. The **
> operator is right-to-left associative, this means x ** y ** z == x ** (y
> ** z). Evaluation is left to right, where it matters [i.e. if one or
> more of the elements here were an expression with side effects]: first x
> is evaluated, then tmp=y**z, then x**tmp. These are two entirely
> different concepts.

Thank you very much for your explanation
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Steven D'Aprano
On Mon, 6 Jun 2016 03:42 am, Random832 wrote:

> On Sun, Jun 5, 2016, at 02:37, Steven D'Aprano wrote:
>> No they don't. You are confusing the implementation with the programming
>> model.
>> 
>> Following the assignment:
>> 
>> x = 99
>> 
>> if you print(x), do you see something like "reference 0x12345"? No.
>> 
>> Do you have to dereference that reference to get the value of x? No.
>>
>> At the Python level, the value of x is 99, not some invisible,
>> untouchable reference to 99.
> 
> Sure, but that is the value of the object referenced by x, it is not a
> property of x itself.

You need to be clear about what you are referring to.

x itself is the object 99. When we say "x + 1", we expect to get 100. x is
not some reference to 99, it is 99, just like Barrack Obama is not a
reference to the President of the United States, he is the POTUS.

The *name* "x" is an entity which is bound to (i.e. a reference to) the
object 99, in some specific namespace, at some specific time. The name
itself is an English word consisting of a single letter, "x". Its
implementation in Python is likely to be a str, "x", used as a key in some
namespace (often a dict). The name itself doesn't have any numeric value,
just as the English words "Barrack Obama" themselves are not a person.

There are contexts where we need to refer to names themselves in Python, but
they are comparatively rare. You will usually recognise them from context,
occasionally implicitly, but usually explicitly by talking about "the name
x" or "x" in quotes rather than x. In code, it will usually involve eval or
exec, or sometimes a namespace lookup:

method = vars(self)[methodname.upper()]


Likewise, it is rare to refer to the words rather than the person Barrack
Obama, but when you do, it is usually easy to recognise because you will
generally refer to "Barrack Obama" in quotes.

We might say:

"x" is a single-letter name and x is an int one less than 100

but you normally wouldn't say:

x is a single-letter name and x is an int one less than 100

unless your aim is to cause confusion.

This is no different from the issue in plain English that words have
meaning, and when we use a word, we normally expect them to be interpreted
according to that meaning, and rarely as an abstract word. When we do, we
normally put it in quotation marks, or explicitly state that we are
referring to it as a word:

A cat is a four-legged carnivorous mammal that purrs. "Cat" is a
three-letter word; the word cat is of unknown origin.



> x = y = 999; z = int('999')
> x is y # True
> x is z # False
> 
> How would you describe the difference between x and y, and z? 

The names x and y are bound to the same object. The name z is bound to a
distinct object with equal value.


> This is not a mere implementation detail 

Of course it is. An implementation might be clever enough to recognise that
int('999') is the same as 999 and reuse the same int object. An
implementation might cache *all* ints, regardless of size, or do no caching
at all. The part of that example which is not implementation defined is
that given x = y = 999, the language requires that x and y be the same
object.


> [though, the fact that for int in 
> particular I had to go higher than 99 to get this result is - I wouldn't
> have had this problem with strings,

Really?

py> a = b = "cat"; c = str("cat")
py> a is b is c
True

But again, this is an implementation detail. The caching of strings depends
on the version and implementation, and the string itself.


> and I *couldn't* have had this 
> problem with lists]. The fact that two objects can have the same value
> while being different objects, and that two variables can point to the
> same object, are part of the programming model.

Right. But that's actually not relevant to the question.


[...]
> The fact that == is an operator distinct from 'is' inherently means that
> variables contain references, not objects.

No, you are mixing levels of explanation and conflating implementation and
interface. Would you insist that because we can say that the words Barack
Obama contain eleven letters that the the United States has two words as a
president? That Michelle Obama is married to two words rather than a man?

Of course not. At least, if you are going to make that argument, then you
are so confused that I'm not even going to discuss this with you.

Imagine a horrendously memory profligate implementation that implemented
variables using the fixed memory location model "variables are boxes". When
I write:

x = y = 999; z = 999

the interpreter creates three boxes "x", "y", "z". All three boxes need to
be big enough for an int object, which in this case is about 12 bytes.
Actually a bit bigger, as you will see: let's say 16 bytes, because the
implementation needs (say) four bytes for an object identity tag. All three
boxes get *mostly* the same content, namely the 12 byte object 999, but the
x and y boxes get the identity tag (lets say) 633988994, and 

Re: Everything good about Python except GUI IDE?

2016-06-05 Thread Michael Torrie
On 03/02/2016 03:36 PM, Marko Rauhamaa wrote:
> Requirements for what I have in mind:
> 
>  1. It would have to be and feel like real Python.
> 
>  2. External commands should be available as callable Python functions.
> 
>  3. Functions/commands should return streams. (Generators, maybe?)
> 
>  4. Pipelines should have an intuitive syntax (but still be valid
> Python).
> 
> Requirements 3 and 4 apply to regular Python code as well.

I've thought about this before and even tried my hand at creating a nice
library for doing this sort of thing with Python.  Generators seem like
a natural analog for the shell pipes. However there is one big problem
with them and that is they can only deal with one stream at a time.
Whereas in shell programming there are 2 streams that you can use and
connect simultaneously.  For example I can simultaneously pipe standard
out from a program to another command whilst piping standard error to
another.  I never figured out a way to emulate this idea of piping
multiple streams.

In the end I decided that Python's superior text processing facilities
eliminated 90% of the reason to use pipes.  And for the other 10%,
generators worked extremely well and efficiently.

http://www.dabeaz.com/generators/Generators.pdf

When I was doing a lot of shell scripting in Python I wrote my own
wrapper routine to launch programs and obtain stdout and stderr, which I
could process with generator filters and that worked fairly elegantly
for many things.  Kind of a half-way approach but it worked well.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Random832
On Sun, Jun 5, 2016, at 23:52, Steven D'Aprano wrote:
> Certainly not. x = y = 999 is required to bind the same object to x and
> y.

My statement was that if two variables can be bound to the same object,
then variables *cannot* contain objects. The object has to exist
somewhere, and this requirement means that the variables cannot be where
the objects live.

> If your variable x were a reference, then we would expect type(x) to
> return
> something like "Reference", but it doesn't, it returns int.

No we would not. You are once again inferring meaning that people's
statements don't actually carry.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-06-05 Thread Michael Torrie
On 06/05/2016 10:01 PM, Michael Torrie wrote:
> I've thought about this before and even tried my hand at creating a nice
> library for doing this sort of thing with Python.  Generators seem like
> a natural analog for the shell pipes. However there is one big problem
> with them and that is they can only deal with one stream at a time.
> Whereas in shell programming there are 2 streams that you can use and
> connect simultaneously.  For example I can simultaneously pipe standard
> out from a program to another command whilst piping standard error to
> another.  I never figured out a way to emulate this idea of piping
> multiple streams.

When I say that Python generators can only deal with one stream at a
time I mean within the context of generator syntax:

for x in gen(gen(gen(...)))

Obviously I could write a function that returns two generators.  It's
just that you can't nest them cleanly.  Not that bash's syntax is
particularly clean when you are messing with standard error as well as
standard out.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-05 Thread Lawrence D’Oliveiro
On Monday, June 6, 2016 at 4:06:20 AM UTC+12, Uri Even-Chen wrote:
> Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
> + 5, without parentheses.

That leads to the code equivalent of 
.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Don't put your software in the public domain

2016-06-05 Thread Nobody
On Sat, 04 Jun 2016 12:28:33 +1000, Steven D'Aprano wrote:

>> OTOH, a Free software licence is unilateral; the author grants the user
>> certain rights, with the user providing nothing in return.
> 
> That's not the case with the GPL.
> 
> The GPL requires the user (not the end-user, who merely avails themselves
> of their common law right to run the software, but the developer user, who
> copies, distributes and modifies the code) to do certain things in return
> for the right to copy, distribute and modify the code:

The GPL places limitations on the granted licence. That isn't the same
thing as requiring the distributor to do something "in return".

This is why the (relatively few) cases where GPL infringements have
resulted in litigation, the legal basis of the litigation is copyright
infringement, not breach of contract.

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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-05 Thread Gregory Ewing

Steven D'Aprano wrote:

The *name* "x" is an entity which is bound to (i.e. a reference to) the
object 99, in some specific namespace, at some specific time. The name
itself is an English word consisting of a single letter, "x".


This is one reason why the term "name" is not good subsitute
for the term "variable". The string "x" is not the same thing
as the variable x, a fact that's obscured if you call the
variable a "name".

A better analogy along the presidential line would be the
name "President of the United States". That name can refer
to different people at different times, so there must be
some piece of state in the world that records the association
between the character string "President of the United States"
and the person who currently holds that office.

It's that piece of state that the OP is calling a "box".
I don't know what form it actually takes, probably an
official piece of paper somewhere, which may well be
kept in a box. But the box doesn't contain Barack Obama
himself, it only contains something that refers to him.

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


Would like to see output of each block of python

2016-06-05 Thread archana . sonavane
Hi Team,

I would like to see output of each block of python.
Don't have any idea about python. What is command to see the output of each 
code block. 


#!/usr/bin/env python

#
# ganglia-api.py - Ganglia Metric API
#


from settings import LOGFILE, PIDFILE, API_SERVER, HEARTBEAT

import os
import sys
import glob
import re
import logging
import socket
import select
import datetime
import time
import SocketServer
from xml.etree import ElementTree
from xml.parsers.expat import ExpatError
from urllib import quote
from threading import Thread

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options


__version__ = '1.0.16'

define("port", default=8080, help="run on the given port", type=int)

logging.basicConfig(level=logging.INFO, format="%(asctime)s 
%(name)s[%(process)d] %(levelname)s - %(message)s",
filename=LOGFILE)
global logger
logger = logging.getLogger("ganglia-api")


class Elem:
def __init__(self, elem):
self.elem = elem

def __getattr__(self, name):
return self.elem.get(name.upper())


class NullElem:
def __getattr__(self, name):
return None


class ApiMetric:
tag_re = re.compile("\s+")

def id(self):
group = self.group if self.group is not None else ""
id_elements = [self.environment, self.grid.name, self.cluster.name, 
self.host.name, group, self.name]
return str.lower(".".join(filter(lambda (e): e is not None, 
id_elements)))

def api_dict(self):
type, units = ApiMetric.metric_type(self.type, self.units, self.slope)
metric = {'environment': self.environment,
  'service': self.grid.name,
  'cluster': self.cluster.name,
  'host': self.host.name,
  'id': self.id(),
  'metric': self.name,
  'instance': self.instance,
  'group': self.group,
  'title': self.title,
  'tags': ApiMetric.parse_tags(self.host.tags),
  'description': self.desc,
  'sum': self.sum,
  'num': self.num,
  'value': ApiMetric.is_num(self.val),
  'units': units,
  'type': type,
  'sampleTime': datetime.datetime.fromtimestamp(
  int(self.host.reported) + int(self.host.tn) - 
int(self.tn)).isoformat() + ".000Z",
  'graphUrl': self.graph_url,
  'dataUrl': self.data_url}
return dict(filter(lambda (k, v): v is not None, metric.items()))

@staticmethod
def parse_tags(tag_string):
if tag_string is None:
return None
else:
tags = ApiMetric.tag_re.split(tag_string)
if "unspecified" in tags:
return list()
else:
return tags

@staticmethod
def metric_type(type, units, slope):
if units == 'timestamp':
return 'timestamp', 's'
if 'int' in type or type == 'float' or type == 'double':
return 'gauge', units
if type == 'string':
return 'text', units
return 'undefined', units

@staticmethod
def is_num(val):
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
return val

def __str__(self):
return "%s %s %s %s %s %s" % (
self.environment, self.grid.name, self.cluster.name, self.host.name, 
self.group, self.name)


class Metric(Elem, ApiMetric):
def __init__(self, elem, host, cluster, grid, environment):
self.host = host
self.cluster = cluster
self.grid = grid
self.environment = environment
Elem.__init__(self, elem)
self.metadata = dict()
for extra_data in elem.findall("EXTRA_DATA"):
for extra_elem in extra_data.findall("EXTRA_ELEMENT"):
name = extra_elem.get("NAME")
if name:
self.metadata[name] = extra_elem.get('VAL')

original_metric_name = self.name

try:
self.metadata['NAME'], self.metadata['INSTANCE'] = 
self.name.split('-', 1)
except ValueError:
self.metadata['INSTANCE'] = ''

if self.name in ['fs_util', 'inode_util']:
if self.instance == 'rootfs':
self.metadata['INSTANCE'] = '/'
else:
self.metadata['INSTANCE'] = '/' + 
'/'.join(self.instance.split('-'))

params = {"environment": self.environment,
  "service": self.grid.name,
  "cluster": self.cluster.name,
  "host": self.host.name,
  "metric": original_metric_name}
url = '%s/ganglia/api/v1/metrics?'