Re: Line terminators in Python?

2017-09-30 Thread Pavol Lisy
On 9/29/17, Rob Gaddi  wrote:
> On 09/29/2017 10:54 AM, Stefan Ram wrote:
>>In some languages, printing »'\n'«, the Unicode code point 10,
>>will have the effect of printing a line terminator, which might
>>mean that the output device actually receives »\r\n«.
>>
>>The line terminator ostensibly depends on the operating
>>system, but actually it depends on the output system. E.g.,
>>under one operating system the console might accept another
>>set of line separators than an editor. (Under Windows,
>>»wordpad« accepts »\n«, while »notepad« requires »\r\n«.)
>>
>>What is the recommended way to terminate a line written with
>>Python? Is it »\n« or something else? For example, in Java,
>>in some cases, one should terminate the line with the value
>>of »java.lang.System.lineSeparator()« which might or might
>>not be equal to the value of »"\n"«.
>>
>>Does it possibly depend on the entity being written to, which
>>might be
>>
>>- the Python console,
>>- the IDLE console,
>>- the operating system console or
>>- a text file?
>>
>
> As everyone else has said; for general purpose (any of your cases) use
> you should always just use '\n' and it automagically works.  The only
> time I've ever needed to explicitly worry about '\r' is communicating
> over sockets or serial ports to devices.  And in those cases you need to
> stuff them with bytes rather than str anyhow, so you're already down in
> the gory bits.
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com

There is also 
https://docs.python.org/3/library/csv.html#csv.Dialect.lineterminator
which (I think) come from RFC4180 (see
http://www.rfc-archive.org/getrfc.php?rfc=4180 search CRLF)

http://www.rfc-archive.org/getrfc.php?rfc=2046 could be also
interesting in this case.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The mysterious ways of Python mailing list

2017-09-30 Thread Thomas Jollans
On 29/09/17 19:15, Vincent Vande Vyvre wrote:
> Is it a reason why my messages appears always a long time (today 9
> hours) on the list after I send it ?
>
> Send at 19:14 UTC+2
>
>
> Vincent
>

Some of my messages take about an hour. From looking at the headers in
these cases, it looks like the delay is always before the message is
received (i.e., accepted) by mail.python.org. This looks like greylisting.

I have no idea why messages "from" regular list users coming through
large, reputable ISPs would be regularly greylisted, but I suppose what
will be will be.


-- Thomas


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


Re: The mysterious ways of Python mailing list

2017-09-30 Thread Skip Montanaro
Some of my messages take about an hour. From looking at the headers in
these cases, it looks like the delay is always before the message is
received (i.e., accepted) by mail.python.org. This looks like greylisting.


Yes, greylisting is one of the anti-spam arrows in the wider on
mail.python.org. However, once your email address has passed that
threshold, new messages from the same address should float through without
delay.

If you have one such message and have the ability to save the entire
original message and all headers to a file (i.e., not Outlook),  you might
want to send it to postmas...@python.org for one of the smart folks there
to investigate.

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


Re: The mysterious ways of Python mailing list

2017-09-30 Thread Tim Golden

On 29/09/2017 18:15, Vincent Vande Vyvre wrote:
Is it a reason why my messages appears always a long time (today 9 
hours) on the list after I send it ?


Vincent,

Your address is being caught in our moderation traps for some reason. At 
the moment I'm away and on-line less than  usual. Perhaps the other 
moderators are likewise less available. So it took a while for anyone to 
get to your post. Often (especially on a working day) we'll get to a 
held post within minutes.


I'm not sure why you're being held; I'll try to see which filter you're 
tripping.


Please do keep posting!

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


The EuroPython Podcast Episode 1

2017-09-30 Thread M.-A. Lemburg
We are happy to announce a new format our Media Workgroup is
experimenting with:

The EuroPython Podcast
--

The podcast intends to be a view on the European Python community. We
will comment and talk about the latest news from the EuroPython
Society last news, interview guests from the European Python community
and discuss future Python events in Europe … and probably more (ideas
are always welcome).

   * EuroPython Podcast Episode 1: RFP & Lasse Schuirmann *

http://blog.europython.eu/post/165899153782/the-europython-podcast-episode-1

In this podcast we discussed about the Venue Request For Proposal
(RFP) for EuroPython 2018, what venues we should aim for? How about a
EuroPython 2018 Disneyland Paris?

Helping with the podcast


If you want to join the podcast as collaborator, nominate someone to
be our next guest, announce your local python conference or/and give
us feedback, please send an email to media...@europython.eu

Many thanks.

Enjoy,
--
EuroPython Media Workgroup Team
http://europython.eu/
http://www.europython-society.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'd like to use "semantic indentation"

2017-09-30 Thread Joonas Liik
On 30 September 2017 at 21:12, Stefan Ram  wrote:

>   I would like to write source code similar to:
>
> country( 'USA' )
>   state( 'Alabama' )
> town( 'Abbeville' )
> town( 'Addison' )
>   state( 'Arizona' )
> town( 'Apache Junction' )
> town( 'Avondale )
> town( 'Benson' )
>
>
you can't get off quite as clean without sth like macropy..
but you can get close with custom contextmanagers.

with country( 'USA' ):
with state( 'Alabama' ):
town( 'Abbeville' )
town( 'Addison' )

of course you need to write the contextmanager yourself..
and need to decide what the topmost level contextmanager will operate on
unless you want to do sth .. .probably quite nasty
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'd like to use "semantic indentation"

2017-09-30 Thread Paul Rubin
r...@zedat.fu-berlin.de (Stefan Ram) writes:
>   I would like to write source code similar to:
> country( 'USA' )
>   state( 'Alabama' ) ...

> It seems I can't do this with Python.  Is there any workaround?

  _= country( 'USA' )
  _=   state( 'Alabama' )
  _= town( 'Abbeville' )
  _= town( 'Addison' )
  _=   state( 'Arizona' )
  _= town( 'Apache Junction' )
  _= town( 'Avondale )
  _= town( 'Benson' )
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'd like to use "semantic indentation"

2017-09-30 Thread Paul Rubin
r...@zedat.fu-berlin.de (Stefan Ram) writes:
>   I would like to write source code similar to:
> country( 'USA' )
>   state( 'Alabama' )

Aside from the workaround that I mentioned, this looks more like data
than code.  Maybe you really want to create a nested structure
(dictionaries, JSON, XML or whatever) and traverse it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I'd like to use "semantic indentation"

2017-09-30 Thread Chris Angelico
On Sun, Oct 1, 2017 at 5:12 AM, Stefan Ram  wrote:
>   I would like to write source code similar to:
>
> country( 'USA' )
>   state( 'Alabama' )
> town( 'Abbeville' )
> town( 'Addison' )
>   state( 'Arizona' )
> town( 'Apache Junction' )
> town( 'Avondale )
> town( 'Benson' )
>
>   using "semantic indentation".
>
>   It seems I can't do this with Python.
>
>   Is there any workaround?

If the indentation has semantic significance, you shouldn't need to
say "country" or "state" or "town". I suggest this format:

USA:
Alabama:
Abbeville
Addison
Arizona:
Apache Junction
Avondale
Benson

and then, as Paul suggested, write a simple parser to read it.

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


Re: I'd like to use "semantic indentation"

2017-09-30 Thread bartc

On 30/09/2017 19:12, Stefan Ram wrote:

   I would like to write source code similar to:

country( 'USA' )
   state( 'Alabama' )
 town( 'Abbeville' )
 town( 'Addison' )
   state( 'Arizona' )
 town( 'Apache Junction' )
 town( 'Avondale )
 town( 'Benson' )

   using "semantic indentation".

   It seems I can't do this with Python.

   Is there any workaround?


 def country(x): print("C:",x)
 def state(x): print("S:",x)
 def town(x): print("T:",x)

 def fn(*a): pass

 fn(
   country( 'USA' ),
 state( 'Alabama' ),
   town( 'Abbeville' ),
   town( 'Addison' ),
 state( 'Arizona' ),
   town( 'Apache Junction' ),
   town( 'Avondale' ),
   town( 'Benson' )
   )


This pretends they are arguments to a dummy function. But it probably 
won't work with anything that isn't also an expression.



--
bartc


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


Re: merits of Lisp vs Python

2017-09-30 Thread Stephan Houben
Op 2017-09-27, Robert L. schreef :
> (sequence-fold + 0 #(2 3 4))
> ===>
> 9
>
> In Python?

>>> sum([2, 3, 4])
9
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: LOOP with fixed final index value

2017-09-30 Thread Stephan Houben
Op 2017-09-27, Robert L. schreef :
>> > (defun myloop (initial final increment)
>> >   (loop for i = initial then (+ i increment)
>> > while (< i final)
>> > do (print i)
>> > finally (let ((i final)) (print i
>> >

> In Python?

myloop = lambda *args: print("{}{}".format("".join(map("{}\n".format,
  range(*args))), args[1]))

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


Re: merits of Lisp vs Python

2017-09-30 Thread Marko Rauhamaa
Stephan Houben :

> Op 2017-09-27, Robert L. schreef :
>> (sequence-fold + 0 #(2 3 4))
>> ===>
>> 9
>>
>> In Python?
>
 sum([2, 3, 4])
> 9

Robert L. is only trolling. He uses fake technical comments to spread
white supremacy in his signatures.


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


newb question about @property

2017-09-30 Thread Bill
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance methods 
__get__(), __set__(), and possibly __del__(), as desired, as I could 
easily provide them with "ideal" customization. Am I overlooking something?


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


Re: newb question about @property

2017-09-30 Thread Ned Batchelder

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance methods 
__get__(), __set__(), and possibly __del__(), as desired, as I could 
easily provide them with "ideal" customization. Am I overlooking 
something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


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


Re: Distributing multiple packages with on setup.py

2017-09-30 Thread Cameron Simpson

On 30Sep2017 00:52, Jimmy Thrasibule  wrote:

I've reorganized my Python project to be under a same name umbrella.
My project can now be seen as multiple subsystems than can depend on
each other. That means that every sub-package can now be distributed
alone so that only required dependencies can be installed.

[...]

The new structure:
   ├─ myproj/
   │  ├─ common/
   │  │  └─ mod1.py
   │  ├─ subpackage1/
   │  ├─ subpackage2/
   │  └─ __init__.py
   └─ setup.py


As you can see not much has changed except that `myproj` is now a
`namespace package
`_
and that sub-packages ``common``, ``subpackage1`` and ``subpackage2``
can now be distributed independently.

Is it possible, still keeping one unique ``setup.py`` file, to create
3 independent packages?

* ``myproj.common``
* ``myproj.subpackage1``
* ``myproj.subpackage2``

Also I'd like to specify that when installing ``myproj.subpackage1``,
``myproj.common`` is required or that ``myproj.subpackage2`` will
require both ``myproj.common`` and ``myproj.subpackage1``.


I do this with my stuff, but instead of keeping a common setup.py I have an 
elaborate and clumsy system that rolls a package or module distro on the fly, 
writing a setup.py file in the process.


So each package/module I publish has a dict names "DISTINFO" in the top level 
file, looking like this:


 DISTINFO = {
 'keywords': ["python2", "python3"],
 'classifiers': [
 "Programming Language :: Python",
 "Programming Language :: Python :: 2",
 "Programming Language :: Python :: 3",
 ],
 'install_requires': [
 'cs.app.flag',
 'cs.env',
 'cs.logutils',
 'cs.pfx',
 'cs.psutils',
 ],
 'entry_points': {
 'console_scripts': [
 'svcd = cs.app.svcd:main'
 ],
 },
 }

This gets fleshed out with a README file containing the module docstring etc.  
So instead of tediously maintaining some uber setup.py I roll a distribution 
directory suitably filled and push that.


This lets me keep the code in a nice shared tree like yours without a heap of 
setup.py files.


Then I have a script to push the latest tagged revision of the module; it makes 
a scratch directory, checks out the relevant files as of the release tag, makes 
the setup.py and README etc, pushes it, then tossed the scratch directory.


I keep a tag for each module release, eg:

 cs.app.svcd 20170906

for the above. A more published module accrues more tags:

 cs.app.megacli 20150118
 cs.app.megacli 20150118.2
 cs.app.megacli 20150118.3
 cs.app.megacli 20150118.4
 cs.app.megacli 20150118.5
 cs.app.megacli 20150801
 cs.app.megacli 20150801.1
 cs.app.megacli 20160225
 cs.app.megacli 20160226
 cs.app.megacli 20160310

The release script looks for the latest one.

Note that this is all one code repo at my end; the script knows how to assemble 
just the relevant files for a particular module.


Cheers,
Cameron Simpson  (formerly c...@zip.com.au)
--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Steve D'Aprano
On Sun, 1 Oct 2017 08:47 am, Bill wrote:

> I spent a few hours experimenting with @property. To my mind it seems
> like it would be preferable to just define (override) instance methods
> __get__(), __set__(), and possibly __del__(), as desired, as I could
> easily provide them with "ideal" customization. Am I overlooking something?

Probably.

This is a particularly simple example, with only getters. How would you write it
by overriding __get__?


class Circle(object):
def __init__(self, centre, radius):
self.centre = centre
self.radius = radius

@property
def diameter(self):
return 2*self.radius

@property
def area(self):
return pi*self.radius**2

@property
def circumference(self):
return pi*self.diameter



-- 
Steve
“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: newb question about @property

2017-09-30 Thread Bill

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance 
methods __get__(), __set__(), and possibly __del__(), as desired, as 
I could easily provide them with "ideal" customization. Am I 
overlooking something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property

Thanks,
Bill


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


Re: Beginners and experts

2017-09-30 Thread ROGER GRAYDON CHRISTMAN
Not in response to any particular note, but to the thread as a whole.

Regarding how beginners make tweaks and changes at random,
hoping that the bug will disappear, where experts tend to be a bit
more methodical in their bug-fixing.

Here at academia I have taught a little bit of partial correctness,
using assertions and what-not to determine whether the code
is correct using mathematical proof techniques.

And then I would ask a test question for them to apply those
proof techniques to a perfectly good function, which contains
no errors of any kind.

And invariably I get those answers that randomly perturb the code instead.
Roger Christman
Pennsylvania State University
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Ned Batchelder

On 9/30/17 7:18 PM, Bill wrote:

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it 
seems like it would be preferable to just define (override) instance 
methods __get__(), __set__(), and possibly __del__(), as desired, as 
I could easily provide them with "ideal" customization. Am I 
overlooking something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property


Can you show us the code you are using it to mimic that?

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


Re: newb question about @property

2017-09-30 Thread Bill

Steve D'Aprano wrote:

On Sun, 1 Oct 2017 08:47 am, Bill wrote:


I spent a few hours experimenting with @property. To my mind it seems
like it would be preferable to just define (override) instance methods
__get__(), __set__(), and possibly __del__(), as desired, as I could
easily provide them with "ideal" customization. Am I overlooking something?

Probably.


You and Ned are both right.  Up until a few minutes ago, I wasn't 
thinking about a class having more than 1 attribute that I wanted to 
change.  And now I realize that __get__ doesn't really make sense in 
that context (in the back of my mind was the notion that @property 
defined __get__, __set__ and __del__) and I allowed that to obscure my 
vision.   I was on the verge of giving up anything to do with computers, 
forever.  : )


BTW, your example (below) is very nice!  I may have seen something 
similar before, but I am starting to appreciate it better now.  I think 
all of this would have made a bit more sense (to me), if instead of just 
"@property", the syntax was "@property.getter".  Now I am forced to ask 
the question, why did they use the underscore (on temperature) in the 
example on the bottom of this page? Is one forced to introduce new 
identifiers in order to define a setter?


https://www.programiz.com/python-programming/property

Thanks!
-Bill



This is a particularly simple example, with only getters. How would you write it
by overriding __get__?


class Circle(object):
 def __init__(self, centre, radius):
 self.centre = centre
 self.radius = radius

 @property
 def diameter(self):
 return 2*self.radius

 @property
 def area(self):
 return pi*self.radius**2

 @property
 def circumference(self):
 return pi*self.diameter





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


Re: newb question about @property

2017-09-30 Thread Bill

Ned Batchelder wrote:

On 9/30/17 7:18 PM, Bill wrote:

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it 
seems like it would be preferable to just define (override) 
instance methods __get__(), __set__(), and possibly __del__(), as 
desired, as I could easily provide them with "ideal" customization. 
Am I overlooking something?




It would be easier to comment if you showed the two options. One 
with @property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your 
real class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property


Can you show us the code you are using it to mimic that?

--Ned.


Here it is, Ned. It's my first attempt at using classes in Python.
I still have to learn how to incorporate datetime appropriately!  :)

import datetime


# object oriented example class Employee(object):
''' This class will abstract an employee. Class date members name, a 
string birthday, a date object address, a string position It also has a 
static data member for the number of employees. ''' num_employees =0 # class data item @classmethod def get_num_employees(cls):

return Employee.num_employees

def __init__(self, name, birthdate, address, position):
Employee.num_employees +=1 self.name = name
self.birthdate = birthdate
self.address = address
self.position = position

@property def address(self):
print("**Hi from address-getter**")
return self._address

@address.setter def address(self, value):
print("*Hi, from address setter()!")
self._address = value


def __del__(self):

print("*** Hi, from __del__()")
##Employee.num_employees -= 1 def __str__(self):
return 'Name: {}, Born: {} \nAddress: {} \nPosition: {} \n'.\
format(self.name,self.birthdate,self.address,self.position)

class SalesPerson(Employee):
def __init__(self, name, bdate, addr):
super().__init__(name, bdate, addr,"Salesperson")


def main():
emp1 = Employee("Sam","4/30/1970","212 Elm","Programmer")
emp2 = SalesPerson("Gene","5/1/79","414 Maple")
## Note: learn to use datetime.date--> str print(emp1)
print(emp2)
emp1.address ="230 Main Street" # call setter? print(emp1)
del(emp1)
print("Number of employees", Employee.get_num_employees())
   




print('*'*30)
main()#call main()

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


Re: newb question about @property

2017-09-30 Thread MRAB

On 2017-10-01 01:07, Bill wrote:

Steve D'Aprano wrote:

On Sun, 1 Oct 2017 08:47 am, Bill wrote:


I spent a few hours experimenting with @property. To my mind it seems
like it would be preferable to just define (override) instance methods
__get__(), __set__(), and possibly __del__(), as desired, as I could
easily provide them with "ideal" customization. Am I overlooking something?

Probably.


You and Ned are both right.  Up until a few minutes ago, I wasn't
thinking about a class having more than 1 attribute that I wanted to
change.  And now I realize that __get__ doesn't really make sense in
that context (in the back of my mind was the notion that @property
defined __get__, __set__ and __del__) and I allowed that to obscure my
vision.   I was on the verge of giving up anything to do with computers,
forever.  : )

BTW, your example (below) is very nice!  I may have seen something
similar before, but I am starting to appreciate it better now.  I think
all of this would have made a bit more sense (to me), if instead of just
"@property", the syntax was "@property.getter".  Now I am forced to ask
the question, why did they use the underscore (on temperature) in the
example on the bottom of this page? Is one forced to introduce new
identifiers in order to define a setter?

https://www.programiz.com/python-programming/property


self._temperature is where the value is actually stored.

Suppose you had this instead:

@temperature.setter
def temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self.temperature = value # <-- changed this line

What would happen when you tried to set the temperature?

Because of the last line, the setter would be calling itself recursively 
until it hit the maximum stack depth.


A leading underscore is the normal convention to indicate that it should 
be treated as "private".


If you wanted the temperature to be read-only, you'd make the value 
"private" and have a getter but not a setter.


[snip]
--
https://mail.python.org/mailman/listinfo/python-list


Re: I'd like to use "semantic indentation"

2017-09-30 Thread Paul Rubin
Chris Angelico  writes:
> USA:
> Alabama:
> Abbeville
> Addison
> ...
> and then, as Paul suggested, write a simple parser to read it.

That looks like YAML, which there's already a library for.  I'm not
crazy about it but it might be an ok choice for this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Cameron Simpson

On 30Sep2017 20:07, Bill  wrote:
think all of this would have made a bit more sense (to me), if instead of just 
"@property", the syntax was "@property.getter".


Perhaps, but nobody wants to type this. Also many properties are ready only, so 
that is the default.


Now I am forced to ask the question, why did they use the underscore (on 
temperature) in the example on the bottom of this page? Is one forced to 
introduce new identifiers in order to define a setter?

https://www.programiz.com/python-programming/property


 class Celsius:
  def __init__(self, temperature = 0):
  self._temperature = temperature
  [...snip...]
  @property
  def temperature(self):
  print("Getting value")
  return self._temperature
  @temperature.setter
  def temperature(self, value):
  if value < -273:
  raise ValueError("Temperat
  print("Setting value")
  self._temperature = value

because the name self.temperature is taken by the property, one must store 
underlying values in a different name. Since the property is one to one with 
the actual internal value here and they're just using the setter protery to do 
a sanity check, they named the internal value very similarly. By using 
"_temperature" they (a) keep the name very similar and (b) make it clear that 
the internal value is "private", not intended for direct use by code outside 
the class.


Cheers,
Cameron Simpson  (formerly c...@zip.com.au)
--
https://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2017-09-30 Thread breamoreboy
On Saturday, September 30, 2017 at 9:03:32 PM UTC+1, Stephan Houben wrote:
> Op 2017-09-27, Robert L. schreef :
> > (sequence-fold + 0 #(2 3 4))
> > ===>
> > 9
> >
> > In Python?
> 
> >>> sum([2, 3, 4])
> 9

Dow you have to keep replying to this out and out racist, as none of his posts 
have any relevance to Python?

--
Kindest regards.

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


Re: newb question about @property

2017-09-30 Thread Steve D'Aprano
On Sun, 1 Oct 2017 11:07 am, Bill wrote:

> You and Ned are both right.  Up until a few minutes ago, I wasn't
> thinking about a class having more than 1 attribute that I wanted to
> change.  And now I realize that __get__ doesn't really make sense in
> that context (in the back of my mind was the notion that @property
> defined __get__, __set__ and __del__) and I allowed that to obscure my
> vision.   I was on the verge of giving up anything to do with computers,
> forever.  : )


property *does* define __get__ and __set__, but not __del__, rather it is called
__delete__. Confusing, I know, but neither __del__ nor __delete__ should be
used very often.

__del__ is the instance destructor. When you have an object:

obj = Some_Class()

and the last reference to that object goes out of scope, the garbage collector
collects the object and reclaims its memory. Before doing so, it calls
obj.__del__ if it exists.

(That's a simplified version.)

__delete__ on the other hand is part of the descriptor protocol, which is how
Python manages:

- methods
- classmethod and staticmethod
- property

and more. Generally speaking, the descriptor protocol is considered "advanced",
not as advanced or scary as metaclasses, but not for beginners either. However,
using property is much less complex.

Properties are *computed attributes*. Here is a grossly simplified explanation
of how Python does attribute look-ups, closer to what Python did in version 1.5
than what it does now, but its a good place to start.

There are three things you can so with an attribute: get it, delete it, or set
it. (A) When you try getting an attribute:

result = obj.spam

the interpreter starts by looking in the object's instance namespace for a
key 'spam':

obj.__dict__['spam']

If it finds it, it returns the associated value and we're done. If not, it next
looks at the object's class:

obj.__class__.__dict__['spam']

and if not, then it looks in any superclasses, then it looks for a __getattr__
method, and finally if all else fails it raises AttributeError.

(B) Deleting an attribute:

del obj.spam

is pretty much the same.

(C) When you try setting an attribute:

obj.spam = eggs

the interpreter assigns to the instance namespace:

obj.__class__.__dict__['spam'] = eggs



So that's (roughly) how Python worked back in 1998 or so, and its still
conceptually close to what happens now. Now let's introduce an extra layer of
complexity: properties[1].

(A) if the result of looking up obj.spam is a property object, then instead of
returning the property object itself, the interpreter calls the property's
getter method, and returns what it returns.

(B) Likewise, deleting the property calls the property's deleter method. (Its
rare to bother with one of them, so in practice you can ignore it.)

(C) And setting obj.spam to a new value calls the property's setter method,
which is intended to handle setting the value somewhere.


(Again, I'm ignoring much of the complexity needed to by the actual
implementation, in order to focus on just the basic conceptual steps.)


 
> BTW, your example (below) is very nice!  I may have seen something
> similar before, but I am starting to appreciate it better now.  I think
> all of this would have made a bit more sense (to me), if instead of just
> "@property", the syntax was "@property.getter".


One of the most common use for properties is read-only attributes, so the
decision was made long ago to have property alone to be equivalent to
property.getter. But if you feel the need, you can write:

@property.getter
def spam(self):
...


but if you do, expect people to look at you funny and say "what's that do?".


> Now I am forced to ask 
> the question, why did they use the underscore (on temperature) in the
> example on the bottom of this page? Is one forced to introduce new
> identifiers in order to define a setter?

Forced to? Not exactly. A computed attribute need not have any storage at all,
or it could only use public attributes, like my earlier Circle example. Circle
didn't use any setters, but I could have let you set the diameter, which in
turn would set the radius:

circle.radius = 2
assert circle.diameter == 4
circle.diameter == 2  # requires a setter
assert circle.radius == 1

Getting that to work is left as an exercise :-)

But most commonly, computed attributes need to store some data aside, somewhere.
You could use a global variable, or write it to a file, or stick it in a list.
All of these things have obvious problems, so the most sensible approach it to
stick the data in a private attribute.

The interpreter doesn't enforce notions of private/public when it comes to
Python classes, but there's a very strong convention that anything starting
with a single underscore is private.



[1] Technically, the interpreter knows nothing about properties. What it cares
about is *descriptors*. Properties are just one kind of descriptor, as are
methods. But I'm intentionally not talking about

Re: merits of Lisp vs Python

2017-09-30 Thread Stephan Houben
Op 2017-09-30, Marko Rauhamaa schreef :
> Robert L. is only trolling. He uses fake technical comments to spread
> white supremacy in his signatures.

My apologies.

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


Re: newb question about @property

2017-09-30 Thread Bill

Steve D'Aprano wrote:

Circle
didn't use any setters, but I could have let you set the diameter, which in
turn would set the radius:

circle.radius = 2
assert circle.diameter == 4
circle.diameter == 2  # requires a setter
assert circle.radius == 1

Getting that to work is left as an exercise :-)


I may start that exercise in a few minutes!



But most commonly, computed attributes need to store some data aside, somewhere.
You could use a global variable, or write it to a file, or stick it in a list.
All of these things have obvious problems, so the most sensible approach it to
stick the data in a private attribute.

The interpreter doesn't enforce notions of private/public when it comes to
Python classes, but there's a very strong convention that anything starting
with a single underscore is private.



[1] Technically, the interpreter knows nothing about properties. What it cares
about is *descriptors*. Properties are just one kind of descriptor, as are
methods. But I'm intentionally not talking about the gory details of
descriptors. Feel free to ask if you care, but honestly, you don't need to care
unless you are writing your own descriptor class.


Thank you, and everyone else who has contributed to this thread, for 
helping me.  Each contribution I read helped me to get further ahead!


I watched an example on YouTube where someone wrote a simple descriptor 
("@Time_it) to output the amount of time that it took ordinary functions 
to complete.To be honest, I AM interested in descriptors. I may 
reexamine whether David Beazley has more to say about them in his book  
"Python: Essential Reference", which I have been reading. Obviously, I 
still have some gaps in my understanding after my first reading.


If you were going to show non-Python users, say science undergraduates 
and faculty, that Python is an interesting tool (in 45 minutes), would 
one delve into descriptors? I am thinking maybe. Here is what I am 
thinking at this moment: trivial applications (probably), list 
comprehensions (definitely), generators (maybe briefly).   Whatever I 
would discuss, I think ending with descriptors could be a strong finish. 
But I'm certainly not merely interested for the sake of my talk, I 
obtain some satisfaction in learning how things work.  If you can 
suggest any references for descriptors which you think are good, I would 
be interested.


Thanks,
Bill

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