Re: A small quiz question
On Wed, Aug 16, 2017 at 7:06 AM, Stefan Ram wrote: > I wrote my first Python quiz question! > > It goes like this: > > Can you predict (without trying it out) what the Python > console will output after the following three lines have > been entered? > > def f(i): print(i); return i; > > f(4)**f(1)**f(2) > > > -- > https://mail.python.org/mailman/listinfo/python-list > That's a nice problem for order evaluation. I guessed wrong. -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays -- https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
On Wed, 16 Aug 2017 09:06 pm, Stefan Ram wrote: > I wrote my first Python quiz question! > > It goes like this: > > Can you predict (without trying it out) what the Python > console will output after the following three lines have > been entered? > > def f(i): print(i); return i; > > f(4)**f(1)**f(2) My initial prediction was: 4 1 2 16 which is embarrassing. Fortunately my supper arrived in the nick of time to distract me from hitting Send, just long enough to remember that 1*1 is 1, not 2. So how about: 4 1 2 4 Unless its a syntax error... I can't remember if the REPL allows multiple semi-colon separated statements after a colon declaration. I know it gets mad at this: py> def a(): pass; def b(): pass File "", line 1 def a(): pass; def b(): pass ^ SyntaxError: invalid syntax So my wild guess is that this is a trick question and the actual answer is that its a SyntaxError. Otherwise, I'm sticking with 4 1 2 4 -- 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: Proposed new syntax
On Tue, 15 Aug 2017 09:10 am, Ben Finney wrote:
> Steve D'Aprano writes:
>
>> On Mon, 14 Aug 2017 07:59 pm, Ben Finney wrote:
>> > You began by asking what people would expect syntax to mean.
>> >
>> > Then you expressed surprise that anyone would think a comprehension
>> > would be interpreted by the reader as a single operation.
>>
>> Yes, and I stand by that.
>
> In the face of the designer saying that's how the feature was intended
> to be interpreted by a reader, you *remain* surprised anyone could think
> that?
Yes. What the designer intended matters not a whit, what matters is what was
actually designed. Whatever Greg intended, it didn't even last long enough to
make it into the PEP, let alone the language.
As I asked Greg earlier:
If he wanted declarative semantics, why didn't he argue for declarative syntax
like "select...where", instead of choosing procedural syntax which matches the
actual procedural semantics given?
In order to think of list comps as declarative, you have to:
- ignore the PEP;
- ignore the documentation;
- ignore the actual behaviour;
- ignore the syntax.
That's a lot of reality to ignore.
That's why I was surprised at your attitude that list comps could reasonably be
interpreted as a single operation. To do so requires ignoring everything we
know about list comprehensions in Python.
The same doesn't apply to map(), at least in Python 2. I think it is completely
reasonable for somebody to imagine that map() operated as a single operation.
They would be wrong, of course, but not egregiously wrong. There's no PEP to
contradict it, the documentation is consistent with map being an atomic
operation:
https://docs.python.org/2/library/functions.html#map
the name is the same as the functional "map", which in purely functional
languages is intended to be read as a mathematical operation which takes a
function and a list and returns a new list.
There may be subtle aspects of map in Python 2 which reveal that it is not
actually a single conceptual operation (side-effects, of course, and the fact
that you can interrupt it with Ctrl-C) but they are subtle and it is reasonable
for somebody to miss them, or to argue that they are mere accidents of
implementation.
But comprehensions? You can't even write a comprehension without being reminded
that they are designed as an expression form of for-loops! That's why I was,
and remain, perplexed that you could ignore the documentation and the behaviour
of comprehensions and believe something so egregiously wrong about them.
> I find it hard to believe you are denying facts to this extent.
I don't know what facts you think I'm ignoring.
>> Python list comprehensions are explicitly documented as being equivalent to a
>> loop, the syntax chosen uses the same keyword as a loop, the implementation
>> uses a loop, and when read as pseudo-code they explicitly claim to be
>> a loop.
>> So on what basis would anyone conclude that they aren't loops?
>
> Python's list comprehensions are explicitly drawn from set theory, the
> syntax chosen uses the same words mathematicians use for set operations.
No they don't. Set builder notation doesn't use words at all, it uses symbols:
{n+1 | n ∈ {1, 2, 3}}
which if we were to translate into words would be:
"the set of n plus one, such that n is an element of the set 1, 2 and 3".
That's not even close to the same words as Python's comprehensions.
Aside: The interesting thing about sets in mathematics is that they're
unordered, unless it is useful for them to be thought of as ordered, in which
case they're taken as ordered. E.g. when talking about arithmetic or geometric
sequences, the unordered set of integers is taken as an ordered set, with no
change in notation or language.
[...]
>> Greg's intention simply doesn't matter. List comprehensions in Python
>> are as they are documented and implemented, not as he intended them to
>> be.
>
> As a statement about what Python *will actually* do, of course that's
> true.
>
> But it's not what you asked, and your bafflement at getting answers not
> to the question you didn't ask, but instead to the question you did ask,
> is becoming quite strange.
I don't understand this. You seem to be implying that the answer to the
question:
"What do you think Python will do if you execute a list comprehension?"
is best answered by predicting that Python will do something that you know it
actually won't do. I can't believe you mean it that way, so I'm more perplexed
than ever.
>> People are free to interpret Python features any way they like, but we
>> don't have to treat them seriously if their interpretation doesn't
>> match the documented semantics of the feature.
>
> Then why ask people's interpretations at the start of this thread?
Because I wanted to know what their interpretations are, and not being
omniscient the only way to do so is to ask.
At no point did I promise that I wouldn't question their answers, if they made
no sense to me.
Re: A small quiz question
[email protected] (Stefan Ram) writes: > I wrote my first Python quiz question! > > It goes like this: > > Can you predict (without trying it out) what the Python > console will output after the following three lines have > been entered? > > def f(i): print(i); return i; > > f(4)**f(1)**f(2) Does Python actually specify what the output will be? It's going to end with 4 (the result from the REPL) and 4, 1 and 2 will appear on the lines before, but is the order they appear specified? -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
On 08/10/2017 04:28 PM, Steve D'Aprano wrote:
Every few years, the following syntax comes up for discussion, with some people
saying it isn't obvious what it would do, and others disagreeing and saying
that it is obvious. So I thought I'd do an informal survey.
What would you expect this syntax to return?
[x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
For comparison, what would you expect this to return? (Without actually trying
it, thank you.)
[x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]
How about these?
[x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100, 200)]
[x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]
Thanks for your comments!
[1,2,3]
[1,2,3,4,5]
SyntaxError("Have you tried Perl ?")
SyntaxError("Have you tried Perl ?")
I really would not want to deal with 3 and 4.
jm
--
https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
On Wed, 16 Aug 2017 10:29 pm, [email protected] wrote: > How do you expect to get four lines of output from the three function calls? In the REPL (the interactive interpreter) the result of evaluating the line is printed. -- 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
Automatic segmenting of large Kafka messages?
When using Apache Kafka, the maximum message size can be defined in the configuration. If you have a lot of similarly sized messages, you can probably make a good estimate of a max message size. When the message sizes are highly variable, that's less certain. This presentation from an engineer at LinkedIn: https://www.slideshare.net/JiangjieQin/handle-large-messages-in-apache-kafka-58692297 describes a Kafka message segmentation facility they created. I poked around looking for an implementation of this concept, but came up short. Before I go off an reimplement the wheel, does anyone know if there is something out there already? I'd be using it with Dana Powers' Kafka package: https://pypi.python.org/pypi/kafka/1.3.4.1 Thx, Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
On Wed, 16 Aug 2017 11:38 pm, Ben Bacarisse wrote: > [email protected] (Stefan Ram) writes: > >> I wrote my first Python quiz question! >> >> It goes like this: >> >> Can you predict (without trying it out) what the Python >> console will output after the following three lines have >> been entered? >> >> def f(i): print(i); return i; >> >> f(4)**f(1)**f(2) > > Does Python actually specify what the output will be? It's going to end > with 4 (the result from the REPL) and 4, 1 and 2 will appear on the > lines before, but is the order they appear specified? https://docs.python.org/3/reference/expressions.html#evaluation-order -- 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: Proposed new syntax
Steve D'Aprano writes: > If he wanted declarative semantics, why didn't he argue for > declarative syntax like "select...where", instead of choosing > procedural syntax which matches the actual procedural semantics given? The syntax “f(foo) for foo in bar if baz(foo)” is nicely declarative. > In order to think of list comps as declarative, you have to: > > - ignore the PEP; > - ignore the documentation; > - ignore the actual behaviour; > - ignore the syntax. > > That's a lot of reality to ignore. Python's list comprehensions behave as I expect that syntax to behave, from the declarative, single-conceptual-operation expression model. I'm not ignoring the behaviour or syntax. The PEP and documentation, I will admit to ignoring (or at least have forgotten since I first read them, now that I've got Python's actual behaviour working with an widely known mental model). The Python behaviour and mental model fit fine together, so I just keep programming on that basis. > That's why I was surprised at your attitude that list comps could > reasonably be interpreted as a single operation. To do so requires > ignoring everything we know about list comprehensions in Python. I hope that clarifies. Everything about how Python's list comprehension behaves, at a Python language level, supports the mental model of a list comprehension as a single conceptual operation. Does Python's behaviour *also* support the mental model of “it's like a for loop”? Yes. Python supports multiple mental models, that should be no surprise. > But comprehensions? You can't even write a comprehension without being > reminded that they are designed as an expression form of for-loops! I'm reminded of a set operation. It works just fine that way. > > […] your bafflement at getting answers not to the question you > > didn't ask, but instead to the question you did ask, is becoming > > quite strange. > > I don't understand this. You seem to be implying that the answer to > the question: > > "What do you think Python will do if you execute a list > comprehension?" You didn't ask about what it *will do*, you asked about syntax that Python does not yet support (a ‘while’ keyword in a list comprehension). The correct answer to “What do you think Python will do if you execute an expression with an invalid keyword in it?” is “Python will raise a SyntaxError”. Indeed, you got just such an answer, and it was an answer to the wrong question as you rightly pointed out at the time. Instead, you asked the much more interesting question: With the ‘while’ keyword in the expression, what do you think Python *would do* if it supported such an expression? So you're asking us not what Python *will in fact* do with that syntax (today, it will raise an error). You're asking us what *the proposed syntax would mean* if Python supported it. > is best answered by predicting that Python will do something that you > know it actually won't do. You're asking something very similar. Because this is *proposed* syntax, presently not valid Python, you're asking us to speculate about some putative future Python, based on our mental models of Python semantics. > But we really haven't established that Python's comprehension > semantics violates any widely established programming language > semantics. Python's comprehension semantics do not violate those widely established semantics, so you can stop waiting for anyone to try establishing that. I'm responding to the proposal by pointing out that, unlike today's Python, the proposed behaviour would violate those semantics. -- \“It is seldom that liberty of any kind is lost all at once.” | `\ —David Hume | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Cross-language comparison: function map and similar
Over in another thread, we've been talking about comprehensions and their similarities and differences from the functional map() operation. Reminder: map(chr, [65, 66, 67, 68]) will return ['A', 'B', 'C']. My questions for those who know languages apart from Python: Are there language implementations which evaluate the result of map() (or its equivalent) in some order other than the obvious left-to-right first-to-last sequential order? Is that order guaranteed by the language, or is it an implementation detail? Standard library functions implementing an explicitly "parallel map" or "threaded map" are also relevant. (Less interested in third-party libraries, unless they're practically a standard for the language in question.) E.g. given the map above, Blub language might promise to evaluate chr(65), chr(66), chr(67) and chr(68) in parallel if your computer has four cores. Or some Blub language implementation may unroll the above map to the equivalent of this pseudo-code: array = [None, None, None, None] array[3] = chr(68) array[2] = chr(67) array[1] = chr(66) array[0] = chr(65) I'm not terribly interested in hypothetical "Blub language doesn't specify evaluation order, so some implementation could do this". I'm more interested in actual concrete examples of mapping implementations which don't operate in the obvious first-to-last order. For example, Fortran has "do concurrent": do concurrent(i = 1:n) a(i) = a(i+m)+b(i) end do which tells the compiler that it can run the iterations in any order, or parallelize them and run them in parallel across threads, etc: https://www.hpcwire.com/2015/04/06/compilers-and-more-the-past-present-and-future-of-parallel-loops/ Wikipedia mentions a few specialised parallel processing languages which have equivalent forms of parallel map: https://en.wikipedia.org/wiki/Map_%28parallel_pattern%29 Wolfram Language (Mathematica?) has a parallel map: http://reference.wolfram.com/language/ref/ParallelMap.html as does Clojure: https://clojuredocs.org/clojure.core/pmap Any others? I'm especially interested in cases of languages where their regular map() function is performed in parallel, or out of order, *without* the performance hit that the Clojure docs warn about: "Only useful for computationally intensive functions where the time of f dominates the coordination overhead." -- 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: A small quiz question
On Wednesday, August 16, 2017 at 12:45:13 PM UTC+1, Steve D'Aprano wrote: > On Wed, 16 Aug 2017 09:06 pm, Stefan Ram wrote: > > > I wrote my first Python quiz question! > > > > It goes like this: > > > > Can you predict (without trying it out) what the Python > > console will output after the following three lines have > > been entered? > > > > def f(i): print(i); return i; > > > > f(4)**f(1)**f(2) > > My initial prediction was: > > > 4 > 1 > 2 > 16 > > > which is embarrassing. Fortunately my supper arrived in the nick of time > to distract me from hitting Send, just long enough to remember that 1*1 > is 1, not 2. > > So how about: > > 4 > 1 > 2 > 4 > > Unless its a syntax error... I can't remember if the REPL allows multiple > semi-colon separated statements after a colon declaration. I know it gets mad > at this: > > py> def a(): pass; def b(): pass > File "", line 1 > def a(): pass; def b(): pass > ^ > SyntaxError: invalid syntax > > > So my wild guess is that this is a trick question and the actual answer is > that > its a SyntaxError. > > Otherwise, I'm sticking with > > 4 > 1 > 2 > 4 > > > > -- > Steve > “Cheer up,” they said, “things could be worse.” So I cheered up, and sure > enough, things got worse. How do you expect to get four lines of output from the three function calls? Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
On 10/08/2017 16:28, Steve D'Aprano wrote: What would you expect this syntax to return? [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5] [1, 2, 3] For comparison, what would you expect this to return? (Without actually trying it, thank you.) [x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5] [1, 2, 3, 4, 5] -- Marco Buttu INAF-Osservatorio Astronomico di Cagliari Via della Scienza n. 5, 09047 Selargius (CA) Phone: 070 711 80 217 Email: [email protected] -- https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
On Wednesday, August 16, 2017 at 2:52:09 PM UTC+1, Steve D'Aprano wrote: > On Wed, 16 Aug 2017 10:29 pm, breamoreboy wrote: > > > How do you expect to get four lines of output from the three function calls? > > In the REPL (the interactive interpreter) the result of evaluating the line is > printed. > > -- > Steve > “Cheer up,” they said, “things could be worse.” So I cheered up, and sure > enough, things got worse. *face palm* but of course. Kindest regards. Mark Lawrence. -- https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
On Thu, 17 Aug 2017 12:28 am, Ben Finney wrote: > Steve D'Aprano writes: > >> If he wanted declarative semantics, why didn't he argue for >> declarative syntax like "select...where", instead of choosing >> procedural syntax which matches the actual procedural semantics given? > > The syntax “f(foo) for foo in bar if baz(foo)” is nicely declarative. Do you consider: for foo in bar: if baz(foo): f(foo) # append to a list, or print, or yield, as needed declarative? My understanding of "declarative" agrees with Wikipedia: "In computer science, declarative programming is a programming paradigm ... that expresses the logic of a computation without describing its control flow." https://en.wikipedia.org/wiki/Declarative_programming For-loops are a classic example of explicitly specifying control flow, so I'm surprised that you seem to think they are declarative. SQL's SELECT ... WHERE is one of the canonical examples of declarative programming: SELECT * FROM Book WHERE price > 100.00 returns matching books (those with a price over 100) in arbitrary order (unless you specify the "ORDER BY" clause). But more importantly than the order of results, the order of data accesses is not specified by the SELECT statement. Instead, the SQL compiler generates a "query plan" that specifies how to access the data: https://en.wikipedia.org/wiki/Query_plan independently of the programmer. (Although many databases offer additional tools for manually fine-tuning the query plan.) If instead we wrote: for row in Book: if row.price > 100: print(row) # for example I think that is specifying the control flow, and therefore not declarative. Do you agree? [...] > I'm responding to the proposal by pointing out that, unlike today's > Python, the proposed behaviour would violate those semantics. In what way? Do you feel the same way about itertools.takewhile? -- 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: Cross-language comparison: function map and similar
On Thu, 17 Aug 2017 12:53 am, Steve D'Aprano wrote: > map(chr, [65, 66, 67, 68]) > > will return ['A', 'B', 'C']. Of course I meant ['A', 'B', 'C', 'D']. -- 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: Cross-language comparison: function map and similar
On Wednesday, August 16, 2017 at 8:24:46 PM UTC+5:30, Steve D'Aprano wrote: > Over in another thread, we've been talking about comprehensions and their > similarities and differences from the functional map() operation. > > Reminder: > > map(chr, [65, 66, 67, 68]) > > will return ['A', 'B', 'C']. > > My questions for those who know languages apart from Python: > > Are there language implementations which evaluate the result of map() (or its > equivalent) in some order other than the obvious left-to-right first-to-last > sequential order? Is that order guaranteed by the language, or is it an > implementation detail? There are dozens of parallel/concurrent languages: https://en.wikipedia.org/wiki/List_of_concurrent_and_parallel_programming_languages > > Standard library functions implementing an explicitly "parallel map" > or "threaded map" are also relevant. Here's the peach (parallel-each) 'adverb in Q/K http://code.kx.com/wiki/Reference/peach In more mainstream languages: parallel map in Julia https://docs.julialang.org/en/latest/manual/parallel-computing Haskell's parmap et al: http://chimera.labs.oreilly.com/books/123000929/ch03.html#sec_par-kmeans-perf -- https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
On Wed, 16 Aug 2017 11:53 pm, jmp wrote:
> On 08/10/2017 04:28 PM, Steve D'Aprano wrote:
>> Every few years, the following syntax comes up for discussion, with some
>> people saying it isn't obvious what it would do, and others disagreeing and
>> saying that it is obvious. So I thought I'd do an informal survey.
>>
>> What would you expect this syntax to return?
>>
>> [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
>>
>>
>> For comparison, what would you expect this to return? (Without actually
>> trying it, thank you.)
>>
>> [x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]
>>
>>
>>
>> How about these?
>>
>> [x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100, 200)]
>>
>> [x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]
>>
>>
>>
>> Thanks for your comments!
>>
>
> [1,2,3]
> [1,2,3,4,5]
> SyntaxError("Have you tried Perl ?")
> SyntaxError("Have you tried Perl ?")
>
> I really would not want to deal with 3 and 4.
:-)
#4 is actually valid syntax right now, and has been since Python 2.2.
py> [x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]
[100, 200, 101, 201, 102, 202, 103, 203, 104, 204]
It is equivalent to:
for x in (0, 1, 2, 999, 3, 4):
if x < 5:
for y in (100, 200):
x + y # collect into the list
--
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: A small quiz question
On Wed, Aug 16, 2017 at 6:51 AM, Dennis Lee Bieber wrote: > On 16 Aug 2017 11:06:26 GMT, [email protected] (Stefan Ram) declaimed > the following: > >> I wrote my first Python quiz question! >> >> It goes like this: >> >> Can you predict (without trying it out) what the Python >> console will output after the following three lines have >> been entered? >> >>def f(i): print(i); return i; >> >>f(4)**f(1)**f(2) >> > > As a first guess > > 2 > 1 > 4 > > 4 > > since in many languages, exponentiation associates right to left I thought the same thing but figured there was no reason to eval f(2) before f(1), so I came up with 1 2 4 4 which is also wrong. -- https://mail.python.org/mailman/listinfo/python-list
Request Help With Gdk.Display
I am working on a program for the Linux platform that
reports system information. The program reports screen
information, number of monitors, resolution of each one
and the total resolution. It does it using a couple of
external utils, Xrandr and Xdpyinfo. It is my goal to
replace the existing code with a python solution without
depending on the external programs.
With the help of a code snippet I found, I came up with
this but it only reports the resolution of the primary
monitor...
#! /usr/bin/env python3
import gi
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
display = Gdk.Display.get_default()
pm = display.get_primary_monitor()
geo = pm.get_geometry()
w = geo.width
h = geo.height
print(w,h)
I know that the number of monitors can be obtained by
using...
mc = Gdk.Display.get_n_monitors(display)
Then to get each monitor, this can be used...
monitor = Gdk.Display.get_monitor(display, monitor_num)
My problem is that I can't find any information on how
"monitor_num" is obtained. The only thing I have been
able to find out is that it is an integer. Can anybody
point me in the right direction? Much appreciated.
--
GNU/Linux user #557453
May the Source be with you.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Cross-language comparison: function map and similar
On 8/16/2017 10:53 AM, Steve D'Aprano wrote: Over in another thread, we've been talking about comprehensions and their similarities and differences from the functional map() operation. Reminder: map(chr, [65, 66, 67, 68]) will return ['A', 'B', 'C']. The comprehension 'while' proposal is for future Python 3. Asking your while question the restricted context of Python 2 encouraged the restricted list-based or concrete-collection-based thinking about comprehensions that you got in some of the answers. The above snipper is only true for Python-2 . In Python 3, >>> oracle = map(chr, [65, 66, 67, 68]) >>> oracle >>> next(oracle) 'A' >>> next(oracle) 'B' >>> next(oracle) 'C' When oracle is asked for the next value, it asks base_oracle = iter(iterable) for a value. If base_oracle gives one, oracle gives func(value). If base_iterable raises StopIteration, so does oracle. This process is inherently sequential. It remains so with multiple input iterables. >>> next(oracle) 'D' >>> next(oracle) Traceback (most recent call last): File "", line 1, in next(oracle) StopIteration Even in pre-2.2 Python, map's input was not restricted to being a list, but could be any 'sequence'. From 2.0 doc: "The list arguments may be *any kind of sequence*" [emphasis added]. I am rather sure that in this context, a 'sequence' was merely something that could be indexed and that a pre-defined length was not required. This means that map could use the old iterator protocol. So 'sequence' meant 'iterator' in current terms. The old spelling of 'next(iterator)' was 'iterator[i]' where i is 0 for the first request for an object and incremented thereafter. The 'sequence' was free to ignore i when generating the return object. It could also use external input. My questions for those who know languages apart from Python: Are there language implementations which evaluate the result of map() (or its equivalent) in some order other than the obvious left-to-right first-to-last sequential order? If map's collection input is unbounded, as with Python, a right-to-left or completely parallel order is not possible. If the input oracle creates objects on demand, as Python allows, then doing anything other that applying func as objects are made available requires internal storage. Asking an oracle for millions of objects when only the first few are needed, is foolish. Storing millions or billions of objects all at once when there are only needed one at a time is also foolish. Which is why map and filter were changed in Python 3. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Gdk.Display
On 2017-08-16 18:57, Wildman via Python-list wrote:
I am working on a program for the Linux platform that
reports system information. The program reports screen
information, number of monitors, resolution of each one
and the total resolution. It does it using a couple of
external utils, Xrandr and Xdpyinfo. It is my goal to
replace the existing code with a python solution without
depending on the external programs.
With the help of a code snippet I found, I came up with
this but it only reports the resolution of the primary
monitor...
#! /usr/bin/env python3
import gi
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
display = Gdk.Display.get_default()
pm = display.get_primary_monitor()
geo = pm.get_geometry()
w = geo.width
h = geo.height
print(w,h)
I know that the number of monitors can be obtained by
using...
mc = Gdk.Display.get_n_monitors(display)
Then to get each monitor, this can be used...
monitor = Gdk.Display.get_monitor(display, monitor_num)
My problem is that I can't find any information on how
"monitor_num" is obtained. The only thing I have been
able to find out is that it is an integer. Can anybody
point me in the right direction? Much appreciated.
If get_n_monitors tells you how many monitors there are, isn't
monitor_num just an index (0, 1, 2, ...)?
--
https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
Ian Kelly : > On Wed, Aug 16, 2017 at 6:51 AM, Dennis Lee Bieber > wrote: >>>def f(i): print(i); return i; >>> >>>f(4)**f(1)**f(2) >>> >> >> As a first guess >> >> 2 >> 1 >> 4 >> >> 4 >> >> since in many languages, exponentiation associates right to left > > I thought the same thing but figured there was no reason to eval f(2) > before f(1), so I came up with > > 1 > 2 > 4 > 4 > > which is also wrong. Python evaluates expressions from left to right. https://docs.python.org/3/reference/expressions.html#evaluati on-order> Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Gdk.Display
On Wed, 16 Aug 2017 19:11:16 +0100, MRAB wrote:
> On 2017-08-16 18:57, Wildman via Python-list wrote:
>> I am working on a program for the Linux platform that
>> reports system information. The program reports screen
>> information, number of monitors, resolution of each one
>> and the total resolution. It does it using a couple of
>> external utils, Xrandr and Xdpyinfo. It is my goal to
>> replace the existing code with a python solution without
>> depending on the external programs.
>>
>> With the help of a code snippet I found, I came up with
>> this but it only reports the resolution of the primary
>> monitor...
>>
>> #! /usr/bin/env python3
>>
>> import gi
>> gi.require_version('Gdk', '3.0')
>> from gi.repository import Gdk
>>
>> display = Gdk.Display.get_default()
>> pm = display.get_primary_monitor()
>> geo = pm.get_geometry()
>> w = geo.width
>> h = geo.height
>> print(w,h)
>>
>>
>> I know that the number of monitors can be obtained by
>> using...
>>
>> mc = Gdk.Display.get_n_monitors(display)
>>
>> Then to get each monitor, this can be used...
>>
>> monitor = Gdk.Display.get_monitor(display, monitor_num)
>>
>> My problem is that I can't find any information on how
>> "monitor_num" is obtained. The only thing I have been
>> able to find out is that it is an integer. Can anybody
>> point me in the right direction? Much appreciated.
>>
> If get_n_monitors tells you how many monitors there are, isn't
> monitor_num just an index (0, 1, 2, ...)?
I don't know. The documentation doesn't say. That is
something I can test that I hadn't thought of. I hope
you are right. It would be nice if it was that simple.
Thanks.
--
GNU/Linux user #557453
The cow died so I don't need your bull!
--
https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Am 15.08.2017 um 20:47 schrieb Larry Hudson: [snip] === test2() code == def test2(alist): ss ─┬─> [1, 2, 3] alist ─┘ - ss ─┬─> [3, 6, 9] alist ─┘ - alist = [30, 60, 90]ss ───> [3, 6, 9] alist ───> [30, 60, 90] [snip] The above shows that with , i.e. assigning single values to individual members of alist (with alist[0]=3 etc.) is "principally" different from assigning a whole list to alist (with alist=[30,60,90]). The first operation doesn't affect the connection between ss and alist, while the second separates the connection between ss and alist, as your diagram above clearly indicates. Isn't this kind of convention/rule something that appears to be not quite natural/"logical" to the common users (non-experts)? M. K. Shen -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 8/16/17 5:06 PM, Mok-Kong Shen wrote: > Am 15.08.2017 um 20:47 schrieb Larry Hudson: > [snip] >>> === test2() code == >>> def test2(alist): ss ─┬─> [1, 2, 3] >>> alist ─┘ >>> - >>> ss ─┬─> [3, 6, 9] >>> alist ─┘ >>> - >>> alist = [30, 60, 90]ss ───> [3, 6, 9] >>> alist ───> [30, 60, 90] > [snip] > > The above shows that with , i.e. assigning single values to > individual members of alist (with alist[0]=3 etc.) is "principally" > different from assigning a whole list to alist (with alist=[30,60,90]). > The first operation doesn't affect the connection between ss and alist, > while the second separates the connection between ss and alist, as your > diagram above clearly indicates. > > Isn't this kind of convention/rule something that appears to be not > quite natural/"logical" to the common users (non-experts)? This kind of question comes up frequently, so you are right, it needs to be learned. But this is true of nearly everything about programming languages, isn't it? Did you take a look at https://nedbatchelder.com/text/names1.html ? It's the best way I know to explain the principles at work here. --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
Steve D'Aprano writes: > On Wed, 16 Aug 2017 11:38 pm, Ben Bacarisse wrote: > >> [email protected] (Stefan Ram) writes: >> >>> I wrote my first Python quiz question! >>> >>> It goes like this: >>> >>> Can you predict (without trying it out) what the Python >>> console will output after the following three lines have >>> been entered? >>> >>> def f(i): print(i); return i; >>> >>> f(4)**f(1)**f(2) >> >> Does Python actually specify what the output will be? It's going to end >> with 4 (the result from the REPL) and 4, 1 and 2 will appear on the >> lines before, but is the order they appear specified? > > https://docs.python.org/3/reference/expressions.html#evaluation-order Thanks. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Default .py program and Edit with IDLE problem
Hello, I installed python 3.6.2 for making running and editing programs. Later on I installed python 2.7 because a program that I downloaded only works with that. Later I deleted the program. I then wanted to run a program from cmd but it was giving me all kinds of errors I didn’t used to get. I thought the problem was being caused by python 2.7 and I didn’t even need it anymore so I uninstalled it. After I uninstalled it, all my .py files’ icons disappeared and when I right clicked on it the “Edit with IDLE” disappeared. I tried all kinds of things like repairing python, editing the registry, etc. but I just can’t fix the problem and this has never happened to me and its really bugging me. Please help. A Python fan -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Gdk.Display
On Wed, 16 Aug 2017 14:33:27 -0500, Wildman wrote:
> On Wed, 16 Aug 2017 19:11:16 +0100, MRAB wrote:
>
>> On 2017-08-16 18:57, Wildman via Python-list wrote:
>>> I am working on a program for the Linux platform that
>>> reports system information. The program reports screen
>>> information, number of monitors, resolution of each one
>>> and the total resolution. It does it using a couple of
>>> external utils, Xrandr and Xdpyinfo. It is my goal to
>>> replace the existing code with a python solution without
>>> depending on the external programs.
>>>
>>> With the help of a code snippet I found, I came up with
>>> this but it only reports the resolution of the primary
>>> monitor...
>>>
>>> #! /usr/bin/env python3
>>>
>>> import gi
>>> gi.require_version('Gdk', '3.0')
>>> from gi.repository import Gdk
>>>
>>> display = Gdk.Display.get_default()
>>> pm = display.get_primary_monitor()
>>> geo = pm.get_geometry()
>>> w = geo.width
>>> h = geo.height
>>> print(w,h)
>>>
>>>
>>> I know that the number of monitors can be obtained by
>>> using...
>>>
>>> mc = Gdk.Display.get_n_monitors(display)
>>>
>>> Then to get each monitor, this can be used...
>>>
>>> monitor = Gdk.Display.get_monitor(display, monitor_num)
>>>
>>> My problem is that I can't find any information on how
>>> "monitor_num" is obtained. The only thing I have been
>>> able to find out is that it is an integer. Can anybody
>>> point me in the right direction? Much appreciated.
>>>
>> If get_n_monitors tells you how many monitors there are, isn't
>> monitor_num just an index (0, 1, 2, ...)?
>
> I don't know. The documentation doesn't say. That is
> something I can test that I hadn't thought of. I hope
> you are right. It would be nice if it was that simple.
> Thanks.
In case anyone is interested that was the answer.
Thanks again MRAB.
--
GNU/Linux user #557453
The cow died so I don't need your bull!
--
https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Am 16.08.2017 um 23:20 schrieb Ned Batchelder: On 8/16/17 5:06 PM, Mok-Kong Shen wrote: Am 15.08.2017 um 20:47 schrieb Larry Hudson: [snip] === test2() code == def test2(alist): ss ─┬─> [1, 2, 3] alist ─┘ - ss ─┬─> [3, 6, 9] alist ─┘ - alist = [30, 60, 90]ss ───> [3, 6, 9] alist ───> [30, 60, 90] [snip] The above shows that with , i.e. assigning single values to individual members of alist (with alist[0]=3 etc.) is "principally" different from assigning a whole list to alist (with alist=[30,60,90]). The first operation doesn't affect the connection between ss and alist, while the second separates the connection between ss and alist, as your diagram above clearly indicates. Isn't this kind of convention/rule something that appears to be not quite natural/"logical" to the common users (non-experts)? This kind of question comes up frequently, so you are right, it needs to be learned. But this is true of nearly everything about programming languages, isn't it? Did you take a look at https://nedbatchelder.com/text/names1.html ? It's the best way I know to explain the principles at work here. I looked at your web page but I don't see at which place in it the issue that I deem to be not natural/"logical" above are (anyway concretely) explained. I apologize, if I have overlooked. I have earlier learned some other (older) programming languages. For these the formal parameters are either "by reference" or "by value". In the first case, any modification of the formal parameter inside a function affects the corresponding actual parameter of a function call, while in the second case a copy of the actual parameter is passed into the function so that any modification of the formal parameter inside the function has no effect at all outside. This is extremely clear-cut in comparison to Python, isn't it? Anyway, while any new user of a programming language certainly can be expected to take good efforts to learn a lot of new stuffs, I suppose it's good for any practical programming language to minimize the cases of surprises for those that come from other programming languages. M. K. Shen -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: > I have earlier learned some other (older) programming languages. For > these the formal parameters are either "by reference" or "by value". > In the first case, any modification of the formal parameter inside > a function affects the corresponding actual parameter of a function > call, while in the second case a copy of the actual parameter is > passed into the function so that any modification of the formal > parameter inside the function has no effect at all outside. This is > extremely clear-cut in comparison to Python, isn't it? Anyway, while > any new user of a programming language certainly can be expected to > take good efforts to learn a lot of new stuffs, I suppose it's good > for any practical programming language to minimize the cases of > surprises for those that come from other programming languages. Python has a data model that is neither of the above, but it's simpler in that you have one pattern for everything. Whether you're looking at function parameters, return values, assignment, loops, function definitions, or anything else, the model is exactly the same. And that model is: objects exist independently of names, and names refer to objects. If you do "x = y", you're saying "figure out which object 'y' means, and make the name 'x' refer to it". If you do "x[1] = y", you're saying "figure out which object 'y' means, and tell the object that 'x' means that it should make [1] refer to that object". So if you have multiple names referring to the same object, any change you ask that object to do will be seen by every other name that also refers to it - because it's all about the object. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Why is my class undefined?
Morning
I haven't ventured into classes much before. When trying to follow some
examples and create my own classes in a jupyter notebook I receive an error
that the class is undefined.
So I created for practise a frog class
class frog(object):
def __init__(self, ftype, word):
self.ftype = ftype
self.word = ftype
def jump(self):
"""
Make frog jump
"""
return "I am jumping"
if __name__ == "__main__":
tree_frog = frog("Tree Frog", "Ribbitt")
print(frog.ftype)
print(frog.word)
I receive this error
NameError Traceback (most recent call last)
in ()
> 1 class frog(object):
2
3 def __init__(self, ftype, word):
4 self.ftype = ftype
5 self.word = ftype
in frog()
12
13 if __name__ == "__main__":
---> 14 tree_frog = frog("Tree Frog", "Ribbitt")
15 print(frog.ftype)
16 print(frog.word)
NameError: name 'frog' is not defined
what exactly am I doing wrong?
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 16Aug2017 23:06, Mok-Kong Shen wrote:
Am 15.08.2017 um 20:47 schrieb Larry Hudson:
[snip]
=== test2() code ==
def test2(alist): ss ─┬─> [1, 2, 3]
alist ─┘
-
ss ─┬─> [3, 6, 9]
alist ─┘
-
alist = [30, 60, 90]ss ───> [3, 6, 9]
alist ───> [30, 60, 90]
[snip]
The above shows that with , i.e. assigning single values to
individual members of alist (with alist[0]=3 etc.) is "principally"
different from assigning a whole list to alist (with alist=[30,60,90]).
The first operation doesn't affect the connection between ss and alist,
while the second separates the connection between ss and alist, as your
diagram above clearly indicates.
Isn't this kind of convention/rule something that appears to be not
quite natural/"logical" to the common users (non-experts)?
Well, it may not seem natural, but it is consistent. Larry's excellent diagrams
have glossed over the lower level of array assignment for clarity.
Observe:
alist = [1,2,3]
This causes "alist" to refer to the list object [1,2,3]. But a list is itself a
compound object with references to its elements. So where Larry drew:
alist ───> [1,2,3]
a more complete diagram looks like this:
alist ───> [ ───> 0,
───> 1,
───> 2
]
so that when you write:
alist[1] = 9
You're dropped the reference to the value 1, and replaced it with a reference
to the value 9:
alist ───> [ ───> 0,
───> 9,
───> 2
]
So you can see that "alist" is a variable name - all python variables are
references to values. So "alist[1]" is also effectively a variable name. What
one would call an "lvalue" in the C programming language: a term that may
appear on the left of an assignment statement.
So they are not funcamentally different activity - what has changed is how you
describe the reference which is being modified.
Consider an object:
class C:
def __init__(self, v0):
self.x = v0
o = C(1)
o2 = C(9)
o.x = 9
o = o2
Here we've made an object with an attribute "x". We make a first instance with
x=1, _bound_ to the name "o". We make another with x=9, bound to the name "o2".
Then:
o.x = 9
changes the reference within the first object to refer to the value 9 instead
of the value 1. It does not change what the name "o" refers to.
Versus:
o = o2
which changes which object the name "o" refers to ("is bound to"): it now
refers to the second object we made.
This is exactly analogous to the array example, but using objects. The notation
eg "alist[1]" or "o.x" is just what you need to say to designate which
reference you are changing.
Cheers,
Cameron Simpson (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why is my class undefined?
On Wed, Aug 16, 2017 at 4:48 PM, Sayth Renshaw wrote:
> Morning
>
> I haven't ventured into classes much before. When trying to follow some
> examples and create my own classes in a jupyter notebook I receive an error
> that the class is undefined.
>
> So I created for practise a frog class
>
> class frog(object):
>
> def __init__(self, ftype, word):
> self.ftype = ftype
> self.word = ftype
>
> def jump(self):
> """
> Make frog jump
> """
> return "I am jumping"
>
> if __name__ == "__main__":
> tree_frog = frog("Tree Frog", "Ribbitt")
> print(frog.ftype)
> print(frog.word)
>
>
> I receive this error
>
> NameError Traceback (most recent call last)
> in ()
> > 1 class frog(object):
> 2
> 3 def __init__(self, ftype, word):
> 4 self.ftype = ftype
> 5 self.word = ftype
>
> in frog()
> 12
> 13 if __name__ == "__main__":
> ---> 14 tree_frog = frog("Tree Frog", "Ribbitt")
> 15 print(frog.ftype)
> 16 print(frog.word)
>
> NameError: name 'frog' is not defined
>
> what exactly am I doing wrong?
The if __name__ == "__main__" block is inside the class declaration
block, so at the point that it runs the class has not been created
yet. Try removing the indentation to place it after the class block
instead.
--
https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Am 17.08.2017 um 00:39 schrieb Chris Angelico: On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: I have earlier learned some other (older) programming languages. For these the formal parameters are either "by reference" or "by value". In the first case, any modification of the formal parameter inside a function affects the corresponding actual parameter of a function call, while in the second case a copy of the actual parameter is passed into the function so that any modification of the formal parameter inside the function has no effect at all outside. This is extremely clear-cut in comparison to Python, isn't it? Anyway, while any new user of a programming language certainly can be expected to take good efforts to learn a lot of new stuffs, I suppose it's good for any practical programming language to minimize the cases of surprises for those that come from other programming languages. Python has a data model that is neither of the above, but it's simpler in that you have one pattern for everything. Whether you're looking at function parameters, return values, assignment, loops, function definitions, or anything else, the model is exactly the same. And that model is: objects exist independently of names, and names refer to objects. If you do "x = y", you're saying "figure out which object 'y' means, and make the name 'x' refer to it". If you do "x[1] = y", you're saying "figure out which object 'y' means, and tell the object that 'x' means that it should make [1] refer to that object". So if you have multiple names referring to the same object, any change you ask that object to do will be seen by every other name that also refers to it - because it's all about the object. I may have misunderstood you. But I don't think what you wrote above would explain why the program below produces the output: [1, 2, 3] [3, 6, 9] M. K. Shen - def test2(alist): alist[0],alist[1],alist[2]=3,6,9 alist=[30,60,90] return def test3(alist): alist=[30,60,90] alist[0],alist[1],alist[2]=3,6,9 return ss=[1,2,3] test3(ss) print(ss) test2(ss) print(ss) -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is my class undefined?
On 17 Aug 2017, at 0:48, Sayth Renshaw wrote: > what exactly am I doing wrong? Outdent the if-statement = jem -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Wed, Aug 16, 2017 at 5:03 PM, Stefan Ram wrote:
> Chris Angelico writes:
>>objects exist independently of names
>
> When the object »Example()« loses its name below,
> it loses its existence.
>
> class Example(object):
> ... def __init__(self):
> ... print( 'initialized' )
> ... def __del__(self):
> ... print( 'deleted' )
> ...
a = Example()
> initialized
a = 2
> deleted
Try:
>>> class Example(object):
... def __init__(self):
... print('initialized')
... def __del__(self):
... print('deleted')
...
>>> a = Example()
initialized
>>> b = [a]
>>> a = 2
>>>
The object no longer has a name, but it still exists.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
Steve D'Aprano writes: > On Thu, 17 Aug 2017 12:28 am, Ben Finney wrote: > > > Steve D'Aprano writes: > > > >> If he wanted declarative semantics, why didn't he argue for > >> declarative syntax like "select...where", instead of choosing > >> procedural syntax which matches the actual procedural semantics given? > > > > The syntax “f(foo) for foo in bar if baz(foo)” is nicely declarative. > > Do you consider [a Python ‘for’ loop] declarative? No, that is a syntax that can only mean iteration over the *distinct statements* in the block. > My understanding of "declarative" agrees with Wikipedia: Thanks. Mine does too. > For-loops are a classic example of explicitly specifying control flow, > so I'm surprised that you seem to think they are declarative. The Python for loop syntax specifies control flow. The Python list comprehension syntax does not specify control flow. The expression “f(foo) for foo in bar if baz(foo)” is not expressing control flow, it is expressing a single conceptual operation. A collection goes in, a single conceptual operation is performed, a collection goes out. The control flow is not specified. > SQL's SELECT ... WHERE is one of the canonical examples of declarative > programming: > > SELECT * > FROM Book > WHERE price > 100.00 > > returns matching books (those with a price over 100) in arbitrary > order (unless you specify the "ORDER BY" clause). But more importantly > than the order of results, the order of data accesses is not specified > by the SELECT statement. Nor is the order of data accesses specified by Python's comprehension syntax. In both cases, of course, implementations *do* perform smaller-grained operations in a specific control flow. You'll even find that order of operations described in the documentation, for SQL implementations and for Python, respectively. > for row in Book: > if row.price > 100: > print(row) # for example > > I think that is specifying the control flow, and therefore not > declarative. Do you agree? Yes, I agree. > [...] > > I'm responding to the proposal by pointing out that, unlike today's > > Python, the proposed behaviour would violate those semantics. > > In what way? By inserting a semantic of iteration over multiple operations, into what is otherwise an expression with declarative semantics. > Do you feel the same way about itertools.takewhile? The functions in the ‘itertools’ module are not expressing a declarative single operation; they are expressing an iteration of multiple operations. List comprehensions, in their syntax, strongly connote a single declarative operation. This makes them different from iteration syntax. -- \ “Shepherds … look after their sheep so they can, first, fleece | `\ them and second, turn them into meat. That's much more like the | _o__) priesthood as I know it.” —Christopher Hitchens, 2008-10-29 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 17Aug2017 01:03, Mok-Kong Shen wrote: Am 17.08.2017 um 00:39 schrieb Chris Angelico: On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: Chris wrote: objects exist independently of names, and names refer to objects. If you do "x = y", you're saying "figure out which object 'y' means, and make the name 'x' refer to it". If you do "x[1] = y", you're saying "figure out which object 'y' means, and tell the object that 'x' means that it should make [1] refer to that object". So if you have multiple names referring to the same object, any change you ask that object to do will be seen by every other name that also refers to it - because it's all about the object. I may have misunderstood you. But I don't think what you wrote above would explain why the program below produces the output: [1, 2, 3] [3, 6, 9] M. K. Shen - def test2(alist): alist[0],alist[1],alist[2]=3,6,9 alist=[30,60,90] return This is because "alist" in the function test2 is a _local_ variable. It is a reference to the same list whose reference was passed to the function. So: alist[0],alist[1],alist[2]=3,6,9 This modifies the references within that list. alist=[30,60,90] This makes the local name "alist" refer to a shiny new list [30,60,90], totally unrelated to the list whose reference was first passed in. Importantly, in the main program "ss" still refers to the original list, which now has references to the values 3, 6 and 9 in it. def test3(alist): alist=[30,60,90] alist[0],alist[1],alist[2]=3,6,9 return This code first points "alist" to a new, unrelated, list. Then modifies the references inside that list. Put different values in this function (by using the same values as in test2 you can see whether changes came from one or the other) eg use 5,6,7 or something. ss=[1,2,3] test3(ss) print(ss) test2(ss) print(ss) So test3 first discards its reference to the [1,2,3] list, then modifies an unrelate new list. So "ss" is unchanged, still holding [1,2,3]. Then test modifies the original list (affecting what "ss" holds) and then points its local "alist" at something else (another shiny new list). But that doesn't change what "ss" refers to, so it now has [3,6,9]. Cheers, Cameron Simpson (formerly [email protected]) -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: > Anyway, while > any new user of a programming language certainly can be expected to > take good efforts to learn a lot of new stuffs, I suppose it's good > for any practical programming language to minimize the cases of > surprises for those that come from other programming languages. Which other languages? Should Python's functions act like C functions, or like Haskell functions? Should Python's strings act like C strings, or Ruby strings? Should Python's syntax be like C syntax, or like Lisp syntax? If languages can't be different from each other, then there's no point in having different languages. I agree that gratuitous differences are, well, gratuitous, but the name/value data model of Python is not some trivial detail that we could change to match some other language: it's a fundamental part of what makes Python what it is. For some reason, students have been taught that things can be either call-by-reference or call-by-value. But those are not the only two possibilities, and neither completely describes how Python works. Learn Python for what it is. --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, Aug 17, 2017 at 9:03 AM, Mok-Kong Shen wrote: > Am 17.08.2017 um 00:39 schrieb Chris Angelico: >> >> On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen >> wrote: >>> >>> I have earlier learned some other (older) programming languages. For >>> these the formal parameters are either "by reference" or "by value". >>> In the first case, any modification of the formal parameter inside >>> a function affects the corresponding actual parameter of a function >>> call, while in the second case a copy of the actual parameter is >>> passed into the function so that any modification of the formal >>> parameter inside the function has no effect at all outside. This is >>> extremely clear-cut in comparison to Python, isn't it? Anyway, while >>> any new user of a programming language certainly can be expected to >>> take good efforts to learn a lot of new stuffs, I suppose it's good >>> for any practical programming language to minimize the cases of >>> surprises for those that come from other programming languages. >> >> >> Python has a data model that is neither of the above, but it's simpler >> in that you have one pattern for everything. Whether you're looking at >> function parameters, return values, assignment, loops, function >> definitions, or anything else, the model is exactly the same. And that >> model is: objects exist independently of names, and names refer to >> objects. If you do "x = y", you're saying "figure out which object 'y' >> means, and make the name 'x' refer to it". If you do "x[1] = y", >> you're saying "figure out which object 'y' means, and tell the object >> that 'x' means that it should make [1] refer to that object". So if >> you have multiple names referring to the same object, any change you >> ask that object to do will be seen by every other name that also >> refers to it - because it's all about the object. > > > I may have misunderstood you. But I don't think what you wrote > above would explain why the program below produces the output: > > [1, 2, 3] > [3, 6, 9] > > M. K. Shen > - > > def test2(alist): > alist[0],alist[1],alist[2]=3,6,9 > alist=[30,60,90] > return > > def test3(alist): > alist=[30,60,90] > alist[0],alist[1],alist[2]=3,6,9 > return > > ss=[1,2,3] > test3(ss) > print(ss) > test2(ss) > print(ss) It does. Go through it step by step. Think about objects and names, not about variables. Also, please keep things on the list - thanks! :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, 17 Aug 2017 08:29 am, Mok-Kong Shen wrote: > I have earlier learned some other (older) programming languages. For > these the formal parameters are either "by reference" or "by value". By reference and by value are not the only two conventions. Perhaps if you go back to the 1950s you might be able to argue that "reference" and "value" are the only two conventions, but alternatives have existed for many decades, since *at least* 1960 when Algol introduced "call by name". Python's evaluation strategy has existed for at least 43 years since Barbara Liskov named the calling convention used by CLU "call by sharing" in 1974. (It actually is much older than CLU, it goes back all the way to Lisp.) https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing > In the first case, any modification of the formal parameter Technically, you cannot modify the formal parameter, because the formal parameter is just a name unbound to any value. It's just the label in the function definition. You need to have actually passed a value as argument to the function before there is anything to modify. > inside > a function affects the corresponding actual parameter of a function > call, while in the second case a copy of the actual parameter is > passed into the function so that any modification of the formal > parameter inside the function has no effect at all outside. This is > extremely clear-cut in comparison to Python, isn't it? Python (and Ruby, Scheme, Ocaml, etc) are very clear-cut too. Just different. This may help: http://import-that.dreamwidth.org/1130.html > Anyway, while > any new user of a programming language certainly can be expected to > take good efforts to learn a lot of new stuffs, I suppose it's good > for any practical programming language to minimize the cases of > surprises for those that come from other programming languages. Indeed. And call by value is surprising: why should passing a giant array of a million values make a copy of the array just because I pass it to a function? And call by reference is even more surprising: if I assign a value to a local name inside a function, why should it modify names in the caller's namespace? Python's evaluation strategy is the least surprising of all the calling strategies I've used. -- Steven D'Aprano “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: A question on modification of a list via a function invocation
Am 17.08.2017 um 01:58 schrieb Cameron Simpson: On 17Aug2017 01:03, Mok-Kong Shen wrote: Am 17.08.2017 um 00:39 schrieb Chris Angelico: On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: Chris wrote: objects exist independently of names, and names refer to objects. If you do "x = y", you're saying "figure out which object 'y' means, and make the name 'x' refer to it". If you do "x[1] = y", you're saying "figure out which object 'y' means, and tell the object that 'x' means that it should make [1] refer to that object". So if you have multiple names referring to the same object, any change you ask that object to do will be seen by every other name that also refers to it - because it's all about the object. I may have misunderstood you. But I don't think what you wrote above would explain why the program below produces the output: [1, 2, 3] [3, 6, 9] M. K. Shen - def test2(alist): alist[0],alist[1],alist[2]=3,6,9 alist=[30,60,90] return This is because "alist" in the function test2 is a _local_ variable. It is a reference to the same list whose reference was passed to the function. So: alist[0],alist[1],alist[2]=3,6,9 This modifies the references within that list. alist=[30,60,90] This makes the local name "alist" refer to a shiny new list [30,60,90], totally unrelated to the list whose reference was first passed in. Importantly, in the main program "ss" still refers to the original list, which now has references to the values 3, 6 and 9 in it. def test3(alist): alist=[30,60,90] alist[0],alist[1],alist[2]=3,6,9 return This code first points "alist" to a new, unrelated, list. Then modifies the references inside that list. Put different values in this function (by using the same values as in test2 you can see whether changes came from one or the other) eg use 5,6,7 or something. ss=[1,2,3] test3(ss) print(ss) test2(ss) print(ss) So test3 first discards its reference to the [1,2,3] list, then modifies an unrelate new list. So "ss" is unchanged, still holding [1,2,3]. Then test modifies the original list (affecting what "ss" holds) and then points its local "alist" at something else (another shiny new list). But that doesn't change what "ss" refers to, so it now has [3,6,9]. I don't yet understand. Why (by which rule of the language reference) should "alist=[30,60,90]" mean discarding the name's reference to the [1,2,3] list? What I conjecture is that in test2 the assignment "alist[0], ..." can only have a proper meaning according to the syntacs of Python if alist is meant to be the global alist. But then, since now the name alist is known to be global, why then in the next line of test2 the name is suddenly interpreted to be local? (Which rule of the language reference says that?) That's what I currently continue to wonder. M. K. Shen M. K. Shen to -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Steve D'Aprano writes: > On Thu, 17 Aug 2017 08:29 am, Mok-Kong Shen wrote: > > > I have earlier learned some other (older) programming languages. For > > these the formal parameters are either "by reference" or "by value". > > By reference and by value are not the only two conventions. > > Perhaps if you go back to the 1950s you might be able to argue that > "reference" and "value" are the only two conventions, but alternatives > have existed for many decades, since *at least* 1960 when Algol > introduced "call by name". Indeed. I have had a lot of success helping people, who come to Python with the baggage of that false dichotomy, by using Fredrik Lundh's term “call by object” to describe the Python argument-pass semantics. Python’s model is neither “call by value” nor “call by reference” (because any attempt to use those terms for Python requires you to use non-standard definitions of the words “-value” and “-reference”). The most accurate description is CLU’s “call by object” or “call by sharing“. Or, if you prefer, “call by object reference“. http://www.effbot.org/zone/call-by-object.htm> > This may help: > > http://import-that.dreamwidth.org/1130.html That's a good one too, thank you for writing it. I just wish Dreamwidth would present a URL with a slug derived from the article title, so that it was easier to search the URLs in my history :-) -- \ “Some people have a problem, and they think “I know, I'll use | `\ Perl!”. Now they have some number of problems but they're not | _o__) sure whether it's a string or an integer.” —Benno Rice, 2011 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is my class undefined?
On Thursday, 17 August 2017 09:03:59 UTC+10, Ian wrote:
wrote:
> > Morning
> >
> > I haven't ventured into classes much before. When trying to follow some
> > examples and create my own classes in a jupyter notebook I receive an error
> > that the class is undefined.
> >
> > So I created for practise a frog class
> >
> > class frog(object):
> >
> > def __init__(self, ftype, word):
> > self.ftype = ftype
> > self.word = ftype
> >
> > def jump(self):
> > """
> > Make frog jump
> > """
> > return "I am jumping"
> >
> > if __name__ == "__main__":
> > tree_frog = frog("Tree Frog", "Ribbitt")
> > print(frog.ftype)
> > print(frog.word)
> >
> >
> > I receive this error
> >
> > NameError Traceback (most recent call last)
> > in ()
> > > 1 class frog(object):
> > 2
> > 3 def __init__(self, ftype, word):
> > 4 self.ftype = ftype
> > 5 self.word = ftype
> >
> > in frog()
> > 12
> > 13 if __name__ == "__main__":
> > ---> 14 tree_frog = frog("Tree Frog", "Ribbitt")
> > 15 print(frog.ftype)
> > 16 print(frog.word)
> >
> > NameError: name 'frog' is not defined
> >
> > what exactly am I doing wrong?
>
> The if __name__ == "__main__" block is inside the class declaration
> block, so at the point that it runs the class has not been created
> yet. Try removing the indentation to place it after the class block
> instead.
Thank you that had me bugged I just couldn't see it.
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
On Thu, 17 Aug 2017 09:12 am, Dennis Lee Bieber wrote: > I suppose, the two in combination imply that the calls to "f()" occur > first in left to right, but then the "**" are applied to the returned > values right to left -- rather than having the calls performed in the > exponentiation order. Standard mathematical convention is for exponentiation to be performed from right to left: 2**3**2 should be evaluated as 2**(3**2) = 512 rather than (2**3)**2 = 64. This is more obvious in the standard formatted mathematical notation where each subsequent index is higher and smaller than the previous, indicating that 2 is being raised to the power of 3 squared, rather than 2 cubed being squared. See, for example, the comment here: http://mathworld.wolfram.com/PowerTower.html where z^z^z is an abbreviation for z^(z^z) (about a third of the way down the page). So Python agrees with the usual maths convention here. -- 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: A question on modification of a list via a function invocation
Mok-Kong Shen writes: > I don't yet understand. Why (by which rule of the language reference) > should "alist=[30,60,90]" mean discarding the name's reference to the > [1,2,3] list? I think I understand that question, but I find it surprising. What is your expectation of the following code? foo = "spam" foo = "beans" print(foo) What should ‘foo’ be bound to after the second assignment? Your question seems to imply you expect that the ‘foo’ reference would be bound to *both* of “"spam"” and “"beans"”, somehow. Is that right? How would that work? To answer the question: The semantics of an assignment statement are at in the Python language reference. Assignment statements are used to (re)bind names to values […] If the target is an identifier (name): […] The name is rebound if it was already bound. https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assignment_stmt> A reference (a name is one kind of reference) can be bound to exactly one object at any time. > But then, since now the name alist is known to be global, why then in > the next line of test2 the name is suddenly interpreted to be local? The same section of the language reference discusses that. In brief: The fact that the first use of a name, in the current scope, is an assignment, means that the name is implicitly within that scope. -- \ “Pinky, are you pondering what I'm pondering?” “Uh, I think so, | `\ Brain, but we'll never get a monkey to use dental floss.” | _o__) —_Pinky and The Brain_ | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Am 17.08.2017 um 02:41 schrieb Steve D'Aprano: On Thu, 17 Aug 2017 08:29 am, Mok-Kong Shen wrote: I have earlier learned some other (older) programming languages. For these the formal parameters are either "by reference" or "by value". By reference and by value are not the only two conventions. Perhaps if you go back to the 1950s you might be able to argue that "reference" and "value" are the only two conventions, but alternatives have existed for many decades, since *at least* 1960 when Algol introduced "call by name". Python's evaluation strategy has existed for at least 43 years since Barbara Liskov named the calling convention used by CLU "call by sharing" in 1974. (It actually is much older than CLU, it goes back all the way to Lisp.) https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing In the first case, any modification of the formal parameter Technically, you cannot modify the formal parameter, because the formal parameter is just a name unbound to any value. It's just the label in the function definition. You need to have actually passed a value as argument to the function before there is anything to modify. inside a function affects the corresponding actual parameter of a function call, while in the second case a copy of the actual parameter is passed into the function so that any modification of the formal parameter inside the function has no effect at all outside. This is extremely clear-cut in comparison to Python, isn't it? Python (and Ruby, Scheme, Ocaml, etc) are very clear-cut too. Just different. This may help: http://import-that.dreamwidth.org/1130.html Anyway, while any new user of a programming language certainly can be expected to take good efforts to learn a lot of new stuffs, I suppose it's good for any practical programming language to minimize the cases of surprises for those that come from other programming languages. Indeed. And call by value is surprising: why should passing a giant array of a million values make a copy of the array just because I pass it to a function? And call by reference is even more surprising: if I assign a value to a local name inside a function, why should it modify names in the caller's namespace? Python's evaluation strategy is the least surprising of all the calling strategies I've used. Sorry for my poor capacity to comprehend. I read in the web page you cited: "In Python, the parameters to a function or method are always local to that function or method. Any assignments to local variables inside the function only affect the local variable, not the caller's variable." But then why in my test2 the global list does get modified? (Would alist[0]=3 etc. be "in-place modification" while alist=[30,60,90] is deemed not an "in-place modification"? If yes, where is that term clearly defined? (That term is new for me.) M. K. Shen M. K. Shen M. K. -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 17Aug2017 02:49, Mok-Kong Shen wrote:
I don't yet understand. Why (by which rule of the language reference)
should "alist=[30,60,90]" mean discarding the name's reference to the
[1,2,3] list?
Section 7.2: Simple statements: Assignment Statements.
It says:
An assignment statement evaluates the expression list (remember that this can
be a single expression or a comma-separated list, the latter yielding a
tuple) and assigns the single resulting object to each of the target lists,
from left to right.
So this:
alist=[30,60,90]
"evaluates the expression list" (that is the [30,60,90]) and assigns it.
So this creates a new list object [30,60,90]. This is independent of whatever
is/was in "alist". Then the reference to that is assigned to the name "alist".
Since a name references to a single object, necessarily the reference to what
"alist" previously refered is discarded.
So before this statement, both "ss" and "alist" referered to the list [1,2,3].
After the statement "ss" has not been changed, and still refers to the [1,2,3]
list. But "alist" now points to the new list which was created by the right
hand side of the assignment statement i.e. the new [30,60,90] list.
You might try inserting some print statements in your code.
print("ss = %s:%r, alist = %s:%r" % (id(ss), ss, id(alist), alist))
after every statement in your code to see these changes. The id() function
returns Python's internal object id for each existing object - this is unique
at any given time. If two names refer to the same object, the same id will be
printed. So this will let you see directly when the names start pointing at
different objects.
You can also go:
print("alist[0] = %s:%r" % (id(alist[0]), alist[0]))
to see the internal things within lists and so forth.
What I conjecture is that in test2 the assignment
"alist[0], ..." can only have a proper meaning according to the syntacs
of Python if alist is meant to be the global alist.
There is no "global alist".
But then, since
now the name alist is known to be global, why then in the next line of
test2 the name is suddenly interpreted to be local?
There are two reasons for this. Firstly, "alist" is a function parameter. That
is a local name, always. Also, every python function definition is inspected
for assignment statements. Any assignment statement "x = ..." causes the name
"x" to be a local variable. This is important, because it provided _reliable_
and predictable behaviour.
(Which rule of
the language reference says that?) That's what I currently continue to
wonder.
4.2. Naming and Binding.
4.2.1 starts "Names refer to objects. Names are introduced by name binding
operations. The following constructs bind names: formal parameters to
functions, ...". So a function parameter is a name binding.
Then "if a name is bound in a block, it is a local variable of that block,
unless declared as nonlocal or global." ("nonlocal" and "global" are explicit
statements.) So a function parameter, which is a binding, causes that name to
be local to the function.
Regarding the inspection side of things to which i alluded to earlier, under
"4.2.2. Resolution of names" it says "If a name binding operation occurs
anywhere within a code block, all uses of the name within the block are treated
as references to the current block. This can lead to errors when a name is used
within a block before it is bound. This rule is subtle. Python lacks
declarations and allows name binding operations to occur anywhere within a code
block. The local variables of a code block can be determined by scanning the
entire text of the block for name binding operations."
Cheers,
Cameron Simpson (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
Am 17.08.2017 um 02:14 schrieb Ned Batchelder: On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen wrote: Anyway, while any new user of a programming language certainly can be expected to take good efforts to learn a lot of new stuffs, I suppose it's good for any practical programming language to minimize the cases of surprises for those that come from other programming languages. Which other languages? Should Python's functions act like C functions, or like Haskell functions? Should Python's strings act like C strings, or Ruby strings? Should Python's syntax be like C syntax, or like Lisp syntax? If languages can't be different from each other, then there's no point in having different languages. I agree that gratuitous differences are, well, gratuitous, but the name/value data model of Python is not some trivial detail that we could change to match some other language: it's a fundamental part of what makes Python what it is. For some reason, students have been taught that things can be either call-by-reference or call-by-value. But those are not the only two possibilities, and neither completely describes how Python works. Learn Python for what it is. Your last sentence is fine and certainly to be accepted. Is there a good document with which one could well use to resolve problems like the present one? (Earlier I learned a few programming languages from their ISO standard documents, which was not easy but later turned out to be quite profitable.) M. K. Shen expect that there be a good documen -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, 17 Aug 2017 10:14 am, Ned Batchelder wrote: > the name/value data model of > Python is not some trivial detail that we could change to match some > other language: it's a fundamental part of what makes Python what it is. It is also an evaluation model which matches nearly all of the most popular languages of the last two decades, including Java[1], Ruby, (I think) PHP, and Javascript. > For some reason, students have been taught that things can be either > call-by-reference or call-by-value. But those are not the only two > possibilities, and neither completely describes how Python works. > > Learn Python for what it is. > > --Ned. Indeed. The insistence on this false dichotomy of call by value versus by reference puzzles me, since alternatives go back to one of earliest, and most influential, programming languages: Lisp. Algol, another early and hugely influential language, used call by name. Its like there was an entire generation of cooks and chefs who insisted that there are only two ways of cooking food: steaming, and barbecuing, and came up with elaborate rationalisations for why frying, roasting, boiling etc are actually one of the two. [1] Despite the obnoxious insistence of Java experts that it is "pass by value", where the value they are talking about is not the actual value, but some hidden, implementation-dependent pointer or reference to the value: http://javadude.com/articles/passbyvalue.htm In the words of the Effbot Fredrik well, I guess you can, in theory, value an artificial number assigned to an object as much as the object itself. "Joe, I think our son might be lost in the woods" "Don't worry, I have his social security number" http://www.effbot.org/zone/call-by-object.htm It absolutely astonishes me how the Java community abuse the term "call by value" in this way, despite the confusion it causes, and despite knowing the correct answer. Scott Stanchfield actually does know what is going on. Despite the inflammatory title of his post, and the outright false comment right at the start: "Java is strictly pass-by-value, exactly as in C." deep in the article linked above, he comes clean and writes: "A correct statement would be /Object references are passed by value/." [emphasis /.../ in original] But the objects themselves are not, as would be required by pass-by-value semantics. So he knows that the values, the objects themselves, are not copied when you pass them to a function. Only the invisible references to the objects are copied, but they are not the values anyone cares about. The example he shows has precisely the same behaviour as the equivalent Python code. -- 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: A question on modification of a list via a function invocation
On Thu, 17 Aug 2017 11:07 am, Stefan Ram wrote: > Steve D'Aprano writes: >>On Thu, 17 Aug 2017 08:29 am, Mok-Kong Shen wrote: >>>In the first case, any modification of the formal parameter >>Technically, you cannot modify the formal parameter, because the formal >>parameter is just a name unbound to any value. It's just the label in the >>function definition. You need to have actually passed a value as argument to >>the function before there is anything to modify. > > So, when an argument is actually passed, then the parameter > can be modified? It seems Mok-Kong Shen was writing about > this case. I would say that the argument is modified. https://docs.python.org/3/faq/programming.html#faq-argument-vs-parameter "Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it." See also: https://docs.python.org/3/glossary.html#term-parameter https://docs.python.org/3/glossary.html#term-argument -- 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
Need some help managing project and making it a little simple (pretty messed up code)
Hello, I am new to python. While learning python, I began a side project. Its a command-line search program. Here: https://github.com/kryptxy/torrench The project is becoming a little difficult to manage, and before it becomes more complex, I'd like to sort it out a little and make it more managable and readable. As of now, I haven't used any OOP concepts (no classes) bc while I was learning, I didn't reach the OOP part, and then spent too much time on the project (and that's probably the part I want help with). Now however, I do know about classes and basics about OOP. But, I am unable to understand how I should begin structuring the project (updating code according to OOP). If someone could have a look? Could really use some suggestions/ideas. Also, can someone point me to some (small) project where something similar is being implemented? (as in sharing similar project-structure). They can be really helpful. I did have a look at youtube-dl source. Not helpful. Seemed too complex. Hope for some positive response. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On Thu, 17 Aug 2017 12:24 pm, Stefan Ram wrote: > Steve D'Aprano writes: >>On Thu, 17 Aug 2017 11:07 am, Stefan Ram wrote: >>>So, when an argument is actually passed, then the parameter >>>can be modified? It seems Mok-Kong Shen was writing about >>>this case. >>I would say that the argument is modified. > > I was thinking along these lines: > def function( parameter ): > ... parameter = parameter + 1 > ... print( parameter ) > ... argument = 4 function( argument ) > 5 argument > 4 Okay, you are talking about the *local variable* called "parameter". We can: - mutate the *object* bound to that local variable; - re-bind (reassign) a different object to that local variable. I was talking about the *name* (an identifier) in the function declaration, a literal piece of text appearing in your source code. In that sense, we can't do anything to the parameter until the function is called and an argument is passed in. I see now that both ways of looking at this have some validity. The FAQ helps a bit: Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. https://docs.python.org/3/faq/programming.html#faq-argument-vs-parameter so in your example the argument is certainly the int 4, the parameter is the name (the identifier) in the function declaration, but how do we refer to the local variable inside the function? Is it the parameter (an identifier) or an argument (an object) or something else? I think the terminology is inconsistent. For example, here: https://chortle.ccsu.edu/java5/Notes/chap34A/ch34A_3.html "formal parameter" is defined as the *identifier* but later on the same page seems to use it to refer to the *local variable*. I think that if we are talking about the local variable when we say "parameter", it is okay to talk about it being re-bound, but if we're talking about the identifier, it is not. -- 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: Cross-language comparison: function map and similar
Steve D'Aprano writes: > Are there language implementations which evaluate the result of map() > (or its equivalent) in some order other than the obvious left-to-right > first-to-last sequential order? Is that order guaranteed by the > language, or is it an implementation detail? Haskell just gives back an unevaluated thunk. The elements are evaluated in whatever order you happen to use them in. Since the evaluation isn't supposed to have observable side effects, there's no way to tell the order. There are also parallel versions (Control.Parallel.Strategies.parMap etc.) and an extension that recognizes "racing stripes" on the square brackets to make list comprehensions run faster: foo = [| sqrt(x) | x <- [1.0 .. 1000.0] |] parallelizes the calculation and offloads it to a GPU or other vector processor. You might also like this old post https://donsbot.wordpress.com/2007/11/29/use-those-extra-cores-and-beat-c-today-parallel-haskell-redux/ "map" is conceptually the lifting of a function from a given type, to the type under the action of some functor. For historical reasons map only works on lists while fmap works on arbitrary functors, but they are in principle the same thing. Depending on what the functor does, the whole concept of left-to-right order might be meaningless. -- https://mail.python.org/mailman/listinfo/python-list
Re: A small quiz question
Dennis Lee Bieber : > I suppose, the two in combination imply that the calls to "f()" > occur first in left to right, but then the "**" are applied to the > returned values right to left -- rather than having the calls > performed in the exponentiation order. Yes, and parentheses, operator precedence or expressions as arguments to functions don't affect the evaluation order. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Default .py program and Edit with IDLE problem
"Kevi Aday (Katch22)" writes: > I installed python 3.6.2 for making running and editing programs. Later on I > installed python 2.7 > because a program that I downloaded only works with that. Later I deleted the > program. I then wanted to run a > program from cmd but it was giving me all kinds of errors I didn’t used to > get. I thought the > problem was being caused by python 2.7 and I didn’t even need it anymore so I > uninstalled it. > After I uninstalled it, all my .py files’ icons disappeared and when I right > clicked on it the “Edit with IDLE” disappeared. > I tried all kinds of things like repairing python, editing the registry, etc. > but I just can’t fix the problem and this > has never happened to me and its really bugging me. Please help. This is obviously a Windows problem. I am no Windows expert but I think this is what happens: both Python 3 as well as Python 2 are using the same Windows configuration resources (i.e. the same resource names) (at least partially). Then, it becomes problematic to install both Python 3 as well as Python 2 in the same Windows system as one version overrides (some of) the other's configuration resources. When you uninstall Python, it likely tries to clean up the Windows configuration - and it is apparently not prepared for the case that is has (partially) overridden another Python version. As a next step, I would try to uninstall and then install again Python 3. -- https://mail.python.org/mailman/listinfo/python-list
Re: Cross-language comparison: function map and similar
On 8/16/17, Steve D'Aprano wrote: > Over in another thread, we've been talking about comprehensions and their > similarities and differences from the functional map() operation. > > Reminder: > > map(chr, [65, 66, 67, 68]) > > will return ['A', 'B', 'C']. > > My questions for those who know languages apart from Python: > > Are there language implementations which evaluate the result of map() (or > its > equivalent) in some order other than the obvious left-to-right first-to-last > sequential order? Is that order guaranteed by the language, or is it an > implementation detail? Is it guaranteed in python? Or future version could implement map with something like subscriptability "propagation"? >>>range(1_000_000_000_000_000_000)[-1] >>> map(lambda a:a+1,range(1_000_000_000_000_000_000))[-1] TypeError: 'map' object is not subscriptable -- https://mail.python.org/mailman/listinfo/python-list
Re: Proposed new syntax
Ben Finney : > The Python list comprehension syntax does not specify control flow. I understand your point, but how do you know your statement is true? I didn't check this, but I would imagine the list comprehension: [ f(x) for x in I if c(x) ] was defined as syntactic sugar for: list(f(x) for x in I if c(x)) where f(x) for x in I if c(x) has heavily iterative semantics. > List comprehensions, in their syntax, strongly connote a single > declarative operation. This makes them different from iteration > syntax. Except for side effects, you get the same result whichever way you imagine it. As a side not, I have found it rather confusing that I have to say: [ (x, y) for x in range(5) for y in range(x) ] instead of: [ (x, y) for y in range(x) for x in range(5) ] After all, you must say: [ ((x, y) for y in range(x)) for x in range(5) ] which, admittedly, means a different thing. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Need some help managing project and making it a little simple (pretty messed up code)
Kryptxy via Python-list writes: > ... > I am new to python. While learning python, I began a side project. Its a > command-line search program. > ... > But, I am unable to understand how I should begin structuring the project > (updating code according to OOP). If someone could have a look? Could really > use some suggestions/ideas. Manageing larger projects is in general helped by some kind of modularization: you split the whole implementation into different parts which have high internal and low external interaction. While the total complexity increases, you have often a chance to concentrate on a part only and this part is far less complex the the whole. OOP is just one kind of modularization. Not all problems can make high use of OOP modularization. For OOP friendly problems, you can easily identify objects. They have state and functions operating on this state (those functions are called "method"s). The state is mostly relevant only for the object internally and less (if at all) for the external world. In your case, the search service itself might be an object. And the queries might be objects. To gain something, you must have interesting operations on those objects - operations that manipulate a mostly irrelevant (but fairly complex) internal state. > Also, can someone point me to some (small) project where something similar is > being implemented? You might have a look at "Products.AdvancedQuery" (--> "PyPI"). Download its source; you will find a documentation in the folder "Products/AdvancedQuery/doc/". It models queries as objects and the relevant operations are query constructors. You (likely) will not be able to "run" it. It depends on a search service called "ZCatalog" (part of the web application framework "Zope"). This search service, too, is implemented by an object. To use it, you would need "Zope". But you can download the source (--> "PyPI"; its name is "Products.ZCatalog") and look at the interface description in "Products.ZCatalog.interfaces.py" to learn about the "ZCatalog" methods. This file also contains a good documentation (via so called "docstring"s). Interfaces are a general way to document the relevant parts of objects/classes for "external use". They are heavily used by "Zope". -- https://mail.python.org/mailman/listinfo/python-list
