[Tutor] Re Module

2018-12-27 Thread Asad
Hi All ,

  I trying find a solution for my script , I have two files :

file1 - I need a search a error say x if the error matches

Look for the same error x in other file 2

Here is the code :
I have 10 different patterns therefore I used list comprehension and
compiling the pattern so I loop over and find the exact pattern matching

re_comp1 = [re.compile(pattern) for pattern in str1]

for pat in re_comp1:
if pat.search(st,re.IGNORECASE):
x = pat.pattern
print x===> here it gives the expected output it correct
match
print type(x)



if re.search('x', line, re.IGNORECASE) is not None:  ===> Gives a wrong
match
  print line

Instead if I use :

if re.search(x, line, re.IGNORECASE) is not None: then no match occurs
  print line

Please advice where I going wrong or what can be done to make it better .

Thanks,


-- 
Asad Hasan
+91 9582111698
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] look back comprehensively

2018-12-27 Thread Mark Lawrence

On 25/12/2018 00:45, Avi Gross wrote:


Please go away as you are so boring :-(

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decomposing a problem

2018-12-27 Thread Mark Lawrence

On 26/12/2018 00:00, Avi Gross wrote:

[Long enough that some should neither read nor comment on.]



PLEASE GO AWAY YOU ARE REALLY IRRITATING.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decomposing a problem

2018-12-27 Thread Steven D'Aprano
On Thu, Dec 27, 2018 at 07:03:18PM +, Mark Lawrence wrote:
> On 26/12/2018 00:00, Avi Gross wrote:
> >[Long enough that some should neither read nor comment on.]
> >
> 
> PLEASE GO AWAY YOU ARE REALLY IRRITATING.

People in glass houses...

Mark, you're not the arbiter of who is allowed to post here. You are 
being obnoxious. Please settle down and perhaps chill a bit. If you 
don't want to read Avi's posts, you know how to hit delete in your mail 
reader don't you?


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decomposing a problem

2018-12-27 Thread Steven D'Aprano
On Wed, Dec 26, 2018 at 11:02:07AM -0500, Avi Gross wrote:

> I often find that I try to make a main point ad people then focus on
> something else, like an example.

I can't speak for others, but for me, that could be because of a number 
of reasons:

- I agree with what you say, but don't feel like adding "I agree" 
after each paragraph of yours;

- I disagree, but can't be bothered arguing;

- I don't understand the point you intend to make, so just move on.

But when you make an obvious error, I tend to respond. This is supposed 
to be a list for teaching people to use Python better, after all.


> So, do we agree on the main point that choosing a specific data structure or
> algorithm (or even computer language) too soon can lead to problems that can
> be avoided if we first map out the problem and understand it better?

Sure, why not? That's vague and generic enough that it has to be true.

But if its meant as advice, you don't really offer anything concrete. 
How does one decide what is "too soon"? How does one avoid design 
paralysis?


> I do not concede that efficiency can be ignored because computers are fast.

That's good, but I'm not sure why you think it is relevant as I never 
suggested that efficiency can be ignored. Only that what people *guess* 
is "lots of data" and what actually *is* lots of data may not be the 
same thing.


> I do concede that it is often not worth the effort or that you can
> inadvertently make things worse and there are tradeoffs.

Okay.


> Let me be specific. The side topic was asking how to get a random key from
> an existing dictionary. If you do this ONCE, it may be no big deal to make a
> list of all keys, index it by a random number, and move on. I did supply a
> solution that might(or might not) run faster by using a generator to get one
> item at a time and stopping when found. Less space but not sure if less
> time.

Why don't you try it and find out?


> But what I often need to do is to segment lots of data into two piles. One
> is for training purposes using some machine learning algorithm and the
> remainder is to be used for verifications. The choice must be random or the
> entire project may become meaningless. So if your data structure was a
> dictionary with key names promptly abandoned, you cannot just call pop()
> umpteen times to get supposedly random results as they may come in a very
> specific order.

Fortunately I never suggested doing that.


> If you want to have 75% of the data in the training section,
> and 25% reserved, and you have millions of records, what is a good way to
> go? 

The obvious solution:

keys = list(mydict.keys())
random.shuffle(keys)
index = len(keys)*3//4
training_data = keys[:index]
reserved = keys[index:]

Now you have the keys split into training data and reserved data. To 
extract the value, you can just call mydict[some_key]. If you prefer, 
you can generate two distinct dicts:

training_data = {key: mydict[key] for key in training_data}

and similarly for the reserved data, and then mydict becomes redundant 
and you are free to delete it (or just ignore it).

Anything more complex than this solution should not even be attempted 
until you have tried the simple, obvious solution and discovered that it 
isn't satisfactory.

Keep it simple. Try the simplest thing that works first, and don't add 
complexity until you know that you need it.

By the way, your comments would be more credible if you had actual 
working code that demonstrates your point, rather than making vague 
comments that something "may" be faster. Sure, anything "may" be faster. 
We can say that about literally anything. Walking to Alaska from the 
southernmost tip of Chile while dragging a grand piano behind you "may" 
be faster than flying, but probably isn't. Unless you have actual code 
backing up your assertions, they're pretty meaningless.

And the advantage of working code is that people might actually learn 
some Python too.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decomposing a problem

2018-12-27 Thread Avi Gross
[Mark Lawrence please press DELETE now in case the rest of this message is
all about you.]
[[If that is not working, if on Windows, try Control-ALT-DELETE as that will
really get rid of my message.]]

Back to replying to Steven,

Of course I want to be corrected when wrong.

I think everyone here knows I tend to be quite expansive in my thoughts and
sometimes to the point where they suggest I am free-associating. I am trying
to get to the point faster and stay there.

So if what I write is not wrong as a general point and you want to bring up
every exception, fine. I reserve the right not to follow you there,
especially not on the forum. I may continue a discussion with you in
private, of course.

I often have a problem in real life (not talking about you, let alone
whoever Mark is) where I think I said something clearly by using phrases
like "if" and find the other person simply acts as if I had left that out.
You know, we can go to the park IF it is not raining tomorrow. Reply is to
tell me the weather report says it will rain so why am I suggesting we go to
the park. Duh. I was not aware of the weather report directly BUT clearly
suggested it was a consideration we should look at before deciding. 

Now a more obvious error should be pointed out. EXAMPLE, I am driving to
Pennsylvania this weekend not far from a National Park and will have some
hours to kill. I suggested we might visit Valley Forge National Historic
Park and did not say only if it was open. Well, in the U.S. we happen to
have the very real possibility the Park will be closed due to it being
deemed optional during a so-called Government Shutdown so such a reply IS
reasonable. I did not consider that and stand corrected.

But Chris, you point out I reacted similarly to what you said. Indeed, you
said that sometimes we don't need to focus on efficiency as compared to
saying we should always ignore it or something like that. I think we
actually are in relative agreement in how we might approach a problem like
this. We might try to solve it in a reasonable way first and not worry at
first about efficiency especially now that some equipment runs so fast and
with so much memory that results appear faster than we can get to them. But,
with experience, and need, we may fine tune code that is causing issues. As
I have mentioned, I have applications that regularly need huge samples taken
at random so a list of millions being created millions of times and the
above being done thousands of times, adds up. Many cheaper methods might
then be considered including, especially, just switching to a better data
structure ONCE.

I will stop this message here as I suspect Mark is still reading and fuming.
Note, I do not intend to mention Mark again in future messages. I do not
actually want to annoy him and wish he would live and let live.

-Original Message-
From: Tutor  On Behalf Of
Steven D'Aprano
Sent: Thursday, December 27, 2018 5:38 PM
To: tutor@python.org
Subject: Re: [Tutor] decomposing a problem

On Wed, Dec 26, 2018 at 11:02:07AM -0500, Avi Gross wrote:

> I often find that I try to make a main point ad people then focus on 
> something else, like an example.

I can't speak for others, but for me, that could be because of a number of
reasons:

- I agree with what you say, but don't feel like adding "I agree" 
after each paragraph of yours;

- I disagree, but can't be bothered arguing;

- I don't understand the point you intend to make, so just move on.

But when you make an obvious error, I tend to respond. This is supposed to
be a list for teaching people to use Python better, after all.


> So, do we agree on the main point that choosing a specific data structure
or
> algorithm (or even computer language) too soon can lead to problems that
can
> be avoided if we first map out the problem and understand it better?

Sure, why not? That's vague and generic enough that it has to be true.

But if its meant as advice, you don't really offer anything concrete. 
How does one decide what is "too soon"? How does one avoid design 
paralysis?


> I do not concede that efficiency can be ignored because computers are
fast.

That's good, but I'm not sure why you think it is relevant as I never 
suggested that efficiency can be ignored. Only that what people *guess* 
is "lots of data" and what actually *is* lots of data may not be the 
same thing.


> I do concede that it is often not worth the effort or that you can
> inadvertently make things worse and there are tradeoffs.

Okay.


> Let me be specific. The side topic was asking how to get a random key from
> an existing dictionary. If you do this ONCE, it may be no big deal to make
a
> list of all keys, index it by a random number, and move on. I did supply a
> solution that might(or might not) run faster by using a generator to get
one
> item at a time and stopping when found. Less space but not sure if less
> time.

Why don't you try it and find out?


> But what I often need to do is to segment l

Re: [Tutor] Re Module

2018-12-27 Thread Alan Gauld via Tutor
On 27/12/2018 15:10, Asad wrote:

> file1 - I need a search a error say x if the error matches
> 
> Look for the same error x in other file 2
> 
> Here is the code :
> I have 10 different patterns therefore I used list comprehension and
> compiling the pattern so I loop over and find the exact pattern matching
> 
> re_comp1 = [re.compile(pattern) for pattern in str1]

I assume str1 is actually a list of strings? You don't
show the definition but since you say it gives the
expected output I'll hope that its correct.

> for pat in re_comp1:
> if pat.search(st,re.IGNORECASE):
> x = pat.pattern
> print x===> here it gives the expected output it correct

I assume st comes from your file1? You don't show us that
bit of code either...

But you do realize that the print only shows the last result.
If there is more than one matching pattern the previous results
get thrown away. And if you only care about one match you
could just use a single regex.
On the other hand, if you do only want the last matching
pattern then what you have works.

> if re.search('x', line, re.IGNORECASE) is not None:  ===> Gives a wrong
> match
>   print line

Notice that you pass the string 'x' into the search.
I assume it is meant to be x? That means you are searching
for the single character 'x' in line. You also don't show
us where line comes from I assume its the other file?

But why do you switch from using the compiled pattern?
Why not just assign x to the pattern object pat? This can
then be used to search line directly and with greater
efficiency.


> if re.search(x, line, re.IGNORECASE) is not None: then no match occurs
>   print line

And are you sure a match should occur?
It would help debug this if you showed us some sample data.
Such as the value of x and the value of line.

Given you are obviously only showing us a selected segment
of your code its hard to be sure. But as written here you
are searching line even if no pattern matches in file1.
That is, you could loop through all your patterns, never
assign anything to x and then go ahead and try to search
for 'x' in line. You should probably check x first.

Also, since you don't show the file looping code we don't
know whether you break out whenever you find a match or
whether the rest of the code is all inside the first
loop over file1. Trying to debug someone else's code
is hard enough. When we only have half the code we are
reduced to guesswork.

Finally, do you get any error messages? If so, please
post them in their entirety. Based on your code I'm
assuming you are working on Python v2.? but its always
worth posting the python version and OS.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Module

2018-12-27 Thread Steven D'Aprano
On Thu, Dec 27, 2018 at 08:40:12PM +0530, Asad wrote:
> Hi All ,
> 
>   I trying find a solution for my script , I have two files :
> 
> file1 - I need a search a error say x if the error matches
> 
> Look for the same error x in other file 2
> 
> Here is the code :
> I have 10 different patterns therefore I used list comprehension and
> compiling the pattern so I loop over and find the exact pattern matching
> 
> re_comp1 = [re.compile(pattern) for pattern in str1]


You can move the IGNORECASE flag into the call to compile. Also, perhaps 
you can use better names instead of "str1" (one string?).

patterns = [re.compile(pattern, re.IGNORECASE) for pattern in string_patterns]
 
> for pat in re_comp1:
> if pat.search(st,re.IGNORECASE):
> x = pat.pattern
> print x===> here it gives the expected output it correct
> match
> print type(x)
> 

Be careful here: even though you have ten different patterns, only *one* 
will be stored in x. If three patterns match, x will only get the last 
of the three and the others will be ignored.

 
> if re.search('x', line, re.IGNORECASE) is not None:  ===> Gives a wrong match

That's because you are trying to match the literal string "x", so it 
will match anything with the letter "x":

box, text, ax, equinox, except, hexadecimal, fix, Kleenex, sixteen ...


> Instead if I use :
> 
> if re.search(x, line, re.IGNORECASE) is not None: then no match occurs
>   print line

Here you are trying to match the variable called x. That is a very bad 
name for a variable (what does "x" mean?) but it should work.

If no match occurs, it probably means that the value of x doesn't occur 
in the line you are looking at.

Try printing x and line and see if they are what you expect them to be:

print x
print line


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dangerous class neighborhood

2018-12-27 Thread Avi Gross
Sometimes when I post something I get back comments and evaluate them and
learn quite a bit. I then reply and debate every little point and it can
continue for a few rounds.

I don't seem to be in that mood today so let me simply restate my entire
post in a few sentences with no examples, no lectures, no advice on what
anyone else can do and very little for anyone to bother replying to. Here
goes:

Sometimes when I run up against a wall and find that a solution to a problem
does not work because things may not work as I expected, I pause. I
reconsider what I actually need to get done. Then I look to see if I can
come up with other ways to do it that will work while still getting the
important parts done. Failing that, I ask if perhaps there is another tool,
such as another programming language that is a better fit for the task. And,
if the work needed seems excessive, I ask if perhaps the problem does not
really need to be solved by me and I move on.

-Original Message-
From: Python-list  On
Behalf Of Chris Angelico
Sent: Thursday, December 27, 2018 5:11 PM
To: Python 
Subject: Re: dangerous class neighborhood

On Fri, Dec 28, 2018 at 8:47 AM Avi Gross  wrote:
> Question 2: Do you want the variables available at the class level or 
> at the instance level?

For constants, definitely put them on the class. They'll be available on
instances as well ("for free", if you like). For mutables, obviously you
need to decide on a case-by-case basis.

> Question 3: Which python variations on syntactic sugar, such as list 
> comprehensions, get expanded invisibly in ways that make the problem 
> happen by asking for variables to be found when no longer in the visible
range?

The oddities with comprehensions were tackled partly during the discussion
of PEP 572. If you want to know exactly why this isn't changing, go read a
few hundred emails on the subject. A lot of the main points are summarized
in the PEP itself:

https://www.python.org/dev/peps/pep-0572/

> There may be matters of efficiency some would consider but some of the 
> examples seen recently seemed almost silly and easy to compute. The 
> people asking about this issue wanted to define a bunch of CONSTANTS, 
> or things that might as well be constants, like this:
>
>
>
> def Foo():
>
> A = ("male", "female", "other")
>
> B = [ kind[0] for kind in A ]# First letters
> only
>
> # And so on making more constants like a dictionary 
> mapping each string to a number or vice versa.
>
>
>
> All the above can be evaluated at the time the class is defined but 
> unintuitive scope rules make some operations fail as variables defined 
> in the scope become unavailable to other things that SEEM to be 
> embedded in the same scope.

If you write simple and Pythonic code, these will almost always work
perfectly. The recent thread citing an oddity worked just fine until it was
written to iterate over range(len(x)) instead of iterating directly.

> If they are ONLY to be used within an instance of Foo or invoked from 
> within there, there may be a fairly simple suggestion. If you already 
> have a __init__ method, then instantiate the variables there carefully 
> using the self object to reference those needed.

But why? __init__ should initialize an instance, not class-level constants.
A Python class is not restricted to just methods, and there's no reason to
avoid class attributes.

> Create a function either outside the class or defined within. Have it 
> do any internal calculations you need in which all internal variables 
> can play nicely with each other. Then let it return all the variables 
> in a tuple like
> this:
>
> def make_sexual_constants():
>
> A = .
>
> B = .
>
> C = f(A,B)
>
> D = .
>
> def Foo():
>
> (A, B, C, D) = make_sexual_constants():

Lovely. Now you have to define your variables once inside the function, then
name them a second time in that function's return statement, and finally
name them all a *third* time in the class statement (at least, I presume
"def Foo():" is meant to be "class Foo:"). A mismatch will create bizarre
and hard-to-debug problems.
What do you actually gain? Can you show me real-world code that would truly
benefit from this?

> Can we agree that the class Foo now has those 4 variables defined and 
> available at either the class level or sub-class or instance levels? 
> But the values are created, again, in a unified safe environment?

Unified? No more so than the class statement itself. Safe? Definitely not,
because of the mandatory duplication of names.

> As noted in section 3, it would be good to know what python features 
> may be unsafe in this kind of context. I had an unrelated recent 
> discussion where it was mentioned that some proposed feature changes 
> might not be thread safe. Valid consideration when that may lead to
hard-to-explain anomalies.

Uhh. nope, th

Re: [Tutor] dangerous class neighborhood

2018-12-27 Thread Steven D'Aprano
On Thu, Dec 27, 2018 at 09:48:02PM -0500, Avi Gross wrote:
> Sometimes when I post something I get back comments and evaluate them and
> learn quite a bit. I then reply and debate every little point and it can
> continue for a few rounds.

I think you sent this to the wrong mailing list. The original post and 
discussion was on Python-List, but you replied to Tutor.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dangerous class neighborhood

2018-12-27 Thread Avi Gross
My apologies. This reply went to the wrong forum.

Hopefully it contains little to be debated. An even shorter version would
be:

If at first you don't succeed ...

-Original Message-
From: Tutor  On Behalf Of Avi
Gross
Sent: Thursday, December 27, 2018 9:48 PM
To: tutor@python.org
Subject: Re: [Tutor] dangerous class neighborhood

Sometimes when I post something I get back comments and evaluate them and
learn quite a bit. I then reply and debate every little point and it can
continue for a few rounds.

I don't seem to be in that mood today so let me simply restate my entire
post in a few sentences with no examples, no lectures, no advice on what
anyone else can do and very little for anyone to bother replying to. Here
goes:

Sometimes when I run up against a wall and find that a solution to a problem
does not work because things may not work as I expected, I pause. I
reconsider what I actually need to get done. Then I look to see if I can
come up with other ways to do it that will work while still getting the
important parts done. Failing that, I ask if perhaps there is another tool,
such as another programming language that is a better fit for the task. And,
if the work needed seems excessive, I ask if perhaps the problem does not
really need to be solved by me and I move on.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Module

2018-12-27 Thread Avi Gross
Asad,

After reading replies to you by Alan and Steven I want to ask you if you can
first tell us in normal words what the exact outline of the program does. If
you only want help on one small part, tell us  about that.

I was first fooled into thinking you wanted to show us how you solve the
majority of the entire problem, whatever it was so I wanted to hear things
like I show next.

An example would be to search two files for error matches of various kinds
and report if they contain any matches. Just report True versus False or
something.

Another goal might be to show the first match in some way then quit.

Another might be to do the same search in two files and report ALL the
matches in some format.

After being clear on the goal, you might specify the overall algorithm you
want to use. For example, do you process one file to completion and save
some results then process the other the same way then compare and produce
output? Or do you process both nearly simultaneously in one pass, or perhaps
multiple passes. Do you search for one error type at a time or all at once?
Can there be multiple errors on the same line of the same kind or different
ones? What does error even mean? Is it something like "Fail: 666" versus
"Warn: 42" or something where multiple errors share a part or ...

Once we have some idea of the goal, we could help you see if the approach
seems reasonable even before reading the code. And, when reading the code,
we might see if your implementation  seems to match the plan so perhaps we
can see where you diverge from it perhaps with a mistake.

If I just look at what you provided, you do some of what I asked. You are
not clear on what the two files contain other than they may have an error
that you can identify with a set of patterns. Can you tell us if you are
looking at one line at a time, assuming it is a text file? Your code shows
no evidence of a file at all. Your focus in what you share with us is mainly
on creating a list of compiled search patterns and applying it to one
uninitialized "st" and trying to figure out which one matched. 

You do not show any examples of the pattern but suggest something is
failing. For all we know one of your patterns just matched the presence of a
single common character or even was not formatted properly and failed to be
compiled.

My impression is you are not actually asking about the overall problem. Your
real question may be how to use a regular expression on a string and find
out what matched. If so, that would be the headline, not about two files.
And it may even be your entire approach could change. An example would be to
store your patterns as a text keyword in a dictionary with the value being
the compiled version so when you evaluate a line using the pattern, you know
which one you matched with. I am NOT saying this is a good solution or a
better one. I am asking you to think what you will need and what techniques
might make life easier in doing it.

So besides trying to alter some code based of the feedback, from others,
could you resubmit the question with a focus on what you are doing and what
exactly is not working that you want looked at. Specifics would be useful
including at least one pattern and a line of sample text that should be
matched by the pattern as an example and perhaps one that should not. And
any error messages are vital.

When you do, I am sure Steven and Alan and others might be able to zoom
right in and help you diagnose, if you don't figure it out by yourself first
by being able to see what your goal is and perhaps doing a little debugging.

-Original Message-
From: Tutor  On Behalf Of
Asad
Sent: Thursday, December 27, 2018 10:10 AM
To: tutor@python.org
Subject: [Tutor] Re Module

Hi All ,

  I trying find a solution for my script , I have two files :

file1 - I need a search a error say x if the error matches

Look for the same error x in other file 2

Here is the code :
I have 10 different patterns therefore I used list comprehension and
compiling the pattern so I loop over and find the exact pattern matching

re_comp1 = [re.compile(pattern) for pattern in str1]

for pat in re_comp1:
if pat.search(st,re.IGNORECASE):
x = pat.pattern
print x===> here it gives the expected output it correct
match
print type(x)



if re.search('x', line, re.IGNORECASE) is not None:  ===> Gives a wrong
match
  print line

Instead if I use :

if re.search(x, line, re.IGNORECASE) is not None: then no match occurs
  print line

Please advice where I going wrong or what can be done to make it better .

Thanks,


--
Asad Hasan
+91 9582111698
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

[Tutor] Interpreter pasting Question

2018-12-27 Thread Avi Gross
This is a serious question. I have tried things and searched and remain
stumped. It is about python and perhaps just the interpreter.

 

Copying and pasting multiple lines into the interpreter fails in mysterious
ways, unless they are a logical single entity.

 

Is there a way to change this behavior, or perhaps an editor/environment
that feeds multiple lines more carefully to the interpreter?

 

I am used to using R Studio and other tools with R. This is not about R but
please permit me an example.

 

I like to be able to tell it in the EDIT window that I want a single line or
a group of lines to be run on the console. That is especially useful when I
am debugging and want to run some code and go to the console and examine
things then continue. I may want to run one line or a region. Clearly
indentation is not an issue there.

 

The python interpreter I use (cpython 3.7.0) on windows lets me copy/paste a
simple single line of code. If it is a complex construct like an if/else
that is syntactically seen as a single statement, it allows it to be copied
in as a unit.

 

But something as simple as this:

 

X=5

Y=6

 

When copied in looks like this:

 

>>> X=5

Y=6

 

SyntaxError: multiple statements found while compiling a single statement

 

Yet I have seen programs that build up a string and give that to eval. Can
those be multiple statements? My tests using eval confuse me. But things I
can type in to the interpreter could be the same after a paste but perhaps
there are reasons they can't be?

 

It may be something as silly as python being too fast and reading all the
input. When I type and hit CARRIAGE RETURN/ENTER it may finish evaluating
before I even start typing the next line. 

 

The current behavior makes it hard to copy code from something like an email
message. Yes, I can (and do) insert the code in a file using IDLE or other
tools then ask to run the file but that is far from the same. Having to copy
one line at a time is beyond frustrating for me.

 

Feel free to tell me I am doing it wrong or of a way that works for others. 

 

Python has an eval() and an exec() and I would assume the latter would be a
way to see what works.

 

Here are three lines using \n:

 

>>> exec("x=6\ny=7\nprint(x+y)")



13

 

That seems to work. Again, if I copied and pasted the same as three lines,
it fails.

 

This works too:

 

>>> dothis = """x=6

y=7

print(x+y)

"""



>>> exec(dothis)



13

 

I did some HW before writing this and some suggest ipython has a better
repr.

 

Some solutions are arguably weird even if they work. One suggestion is to
wrap it all in an if that is always true and indent all subsequent lines:

 

if 1:

x = 6

y = 7

print(x+y)

 

When I do a copy and paste of that including the otherwise meaningless if
statement, it works:

 

>>> if 1:

x = 6

y = 7

print(x+y)

 

13

 

So, sure, I can stick nonsense in but wonder if there is a reasonable trick
like setting options to the interpreter or using an editor that feeds lines
slowly or .

 

But, yes, I can live with this or perhaps learn how to use a debugger than
might let me run things with breakpoints or .

 

 

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interpreter pasting Question

2018-12-27 Thread Steven D'Aprano
On Fri, Dec 28, 2018 at 12:58:00AM -0500, Avi Gross wrote:

[...]
> Copying and pasting multiple lines into the interpreter fails in mysterious
> ways, unless they are a logical single entity.
> 
> Is there a way to change this behavior, or perhaps an editor/environment
> that feeds multiple lines more carefully to the interpreter?

Which interpreter are you using?

If it is the regular Python REPL (Read Eval Print Loop), then pasting 
multiple lines should work, with some limitations. For example, I can 
paste:

x = 5
y = 6

as two lines, and it works fine under Linux. I see no reason why it 
should be different under Windows.

If you just run "python" in the Windows shell (cmd.exe or whatever its 
called), you should get an interactive interpreter. What happens when 
you paste multiple lines in that?



[...]
> When copied in looks like this:
> 
> >>> X=5
> 
> Y=6
> 
> SyntaxError: multiple statements found while compiling a single statement

That looks like a bug. Are you using IDLE? Perhaps it has been fixed 
in newer versions of Python, and if not, you should report it as a 
bug on the bugtracker

https://bugs.python.org/

but:

(1) try searching for similar bug reports first;
(2) read this first: 

http://www.sscce.org/

(3) and do try to keep your bug report short and to the point.


It looks like others have this problem with IDLE too:

https://duckduckgo.com/?q=idle+paste+multiple+lines


IPython/Jupyter allows pasting of multiple lines; I expect that bpython 
will too.

https://ipython.org/

https://bpython-interpreter.org/


But as I said, the vanilla Python REPL ought to work. How are you 
starting the interpreter? My guess is that you're using IDLE.



[...]
> Python has an eval() and an exec() and I would assume the latter would be a
> way to see what works.

No, exec() executes Python code, it doesn't try to simulate a REPL.


> Here are three lines using \n:
> 
> >>> exec("x=6\ny=7\nprint(x+y)")
> 13
>
> 
> That seems to work. Again, if I copied and pasted the same as three lines,
> it fails.

Without knowing the system you are using, and how you copy and paste, it 
is hard to comment except to say "Works for me". Here are three lines:

x = 6
y = 7
print(x + y)


If I select those three lines with the mouse, copy, then paste into a 
standard Python interactive interpreter, I get this:


py> x = 6
py> y = 7
py> print(x + y)
13


exactly as expected. But if I do it in IDLE, I get this:

>>> x = 6
y = 7
print(x + y)

SyntaxError: multiple statements found while compiling a single 
statement
>>> 

That *really* sounds like a bug to me. But perhaps I just don't 
understand IDLE.




-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor