re.search when used within an if/else fails

K

Kevin T

python version 2.4.3, yes i know that it is old. getting the sysadmin to update the OS requires a first born.

with the following code..
for signal in register['signals'] :

351 sigName = signal['functionName']
352 if re.search( "rsrvd", sigName ) == None :
353 print sigName
354 newVal = "%s%s" % ( '1'*signal['bits'] , newVal ) #prepend 0's
355 if re.search( "rsrvd", sigName ) != None :
356 print sigName
357 newVal = "%s%s" % ( '0'*signal['bits'], newVal )

regardless of how i code line 352, i can not EVER use an else clause with it. if i use an else clause, the else will NEVER get executed...

has any one experienced anything like this behavior? any suggestions? the above code works but... why should i have to code it like this?

kevin
 
M

MRAB

python version 2.4.3, yes i know that it is old. getting the sysadmin to update the OS requires a first born.

with the following code..
for signal in register['signals'] :

351 sigName = signal['functionName']
352 if re.search( "rsrvd", sigName ) == None :
353 print sigName
354 newVal = "%s%s" % ( '1'*signal['bits'] , newVal ) #prepend 0's
355 if re.search( "rsrvd", sigName ) != None :
356 print sigName
357 newVal = "%s%s" % ( '0'*signal['bits'], newVal )

regardless of how i code line 352, i can not EVER use an else clause with it. if i use an else clause, the else will NEVER get executed...

has any one experienced anything like this behavior? any suggestions? the above code works but... why should i have to code it like this?
Have you checked the indentation? There may be a mixture of tabs and spaces.

A couple of points:

1. You should be using "is None" and "is not None" instead of "== None"
and "!= None".

2. You don't need to use regex. Use "rsrvd" in sigName and "rsrvd" not
in sigName.
 
S

Steven D'Aprano

python version 2.4.3, yes i know that it is old. getting the sysadmin
to update the OS requires a first born.

with the following code..
for signal in register['signals'] :

351 sigName = signal['functionName'] 352
if re.search( "rsrvd", sigName ) == None : 353
print sigName 354 newVal = "%s%s" % (
'1'*signal['bits'] , newVal ) #prepend 0's 355 if
re.search( "rsrvd", sigName ) != None : 356 print
sigName 357 newVal = "%s%s" % ( '0'*signal['bits'],
newVal )


Your code is mangled to the point of unreadability.

Please resend, and make sure you send it as PLAIN TEXT and not as HTML
("rich text"), since many mail programs feel that they are allowed to
arbitrarily rewrap HTML text however they like.

Preferably simplify your example to the simplest example that we can run:

http://sscce.org/

Being able to run it means you shouldn't put line numbers on the left. If
you must draw our attention to a specific line, use a comment. This isn't
1975 and we're not programming in BASIC.

# BAD don't do this:
350 do_this(x)
351 do_that(y, z)
352 if something:
353 do_something_else(x, y, z)


# GOOD do this:
do_this(x)
do_that(y, z)
if something: # LINE 352
do_something_else(x, y, z)



regardless of how i code line 352, i can not EVER use an else clause
with it. if i use an else clause, the else will NEVER get executed...

The code you show doesn't actually have an `else` clause, which might
explain why it doesn't get executed.

By the way, you should not write "if something == None", always use "if
something is None" or "is not None". Technically, there are some
exceptions but if you have to ask what they are, you don't need to know
*wink*
 
S

Steven D'Aprano

Your code is mangled to the point of unreadability.

Ah, never mind, that's *my* fault, not yours. Or rather, my news reader
software. Sorry about the noise.

The rest of my post still stands:


- simplify your example to the simplest example that we can run
http://sscce.org/

- don't put line numbers at the start of lines

- your code doesn't have an else clause

- use "if something is None", not == None.
 
K

Kevin T

On Tue, 20 Nov 2012 01:24:54 +0000, Steven D'Aprano wrote:



- use "if something is None", not == None.


Steven

i will not include line #'s in the future, point taken
i will change ==/!= to is/is not as most people pointed out.

there is no else because it doesn't work.

i used eclipse in debug mode and a command line execution of the code, both behave the same way

#if re.search( "rsrvd", sigName ) : #version a
#if re.search( "rsrvd", sigName ) == None : #version b
if re.search( "rsrvd", sigName ) is None : #version bb
print sigName
newVal = "%s%s" % ('1'*signal['bits'] , newVal )
#else: #version c
if re.search( "rsrvd", sigName ) != None : #version d
print sigName
newVal = "%s%s" % ( '0'*signal['bits'],> newVal )

i can use either version a/b the else clause (version c) will not execute.
fortunately, with version bb, the else clause will execute!!

thanks for the input all..

kevin

Now if i change
 
I

Ian Kelly

#if re.search( "rsrvd", sigName ) : #version a
#if re.search( "rsrvd", sigName ) == None : #version b
if re.search( "rsrvd", sigName ) is None : #version bb
print sigName
newVal = "%s%s" % ('1'*signal['bits'] , newVal )
#else: #version c
if re.search( "rsrvd", sigName ) != None : #version d
print sigName
newVal = "%s%s" % ( '0'*signal['bits'],> newVal )

i can use either version a/b the else clause (version c) will not execute.
fortunately, with version bb, the else clause will execute!!

There must be some other difference in your testing. I don't have
Python 2.4 available, but I tried your version a in both Python 2.3
and 2.5 using made-up values for sigName, and the else clause is
executed in both.
 
I

Ian Kelly

#if re.search( "rsrvd", sigName ) : #version a
#if re.search( "rsrvd", sigName ) == None : #version b
if re.search( "rsrvd", sigName ) is None : #version bb
print sigName
newVal = "%s%s" % ('1'*signal['bits'] , newVal )
#else: #version c
if re.search( "rsrvd", sigName ) != None : #version d
print sigName
newVal = "%s%s" % ( '0'*signal['bits'],> newVal )

i can use either version a/b the else clause (version c) will not execute.
fortunately, with version bb, the else clause will execute!!

There must be some other difference in your testing. I don't have
Python 2.4 available, but I tried your version a in both Python 2.3
and 2.5 using made-up values for sigName, and the else clause is
executed in both.

It should be noted, however, that version a is the logical *inverse*
of both b and bb. With version a, you're testing for the logical
truth of the re.search result; it will be true if it is *not* None.
With the other two you are testing that the result *is* None.
 
K

Kevin T

#if re.search( "rsrvd", sigName ) :   #version a
#if re.search( "rsrvd", sigName ) == None :   #version b
if re.search( "rsrvd", sigName ) is None :   #version bb
   print sigName
   newVal = "%s%s" % ('1'*signal['bits'] , newVal )
#else:                                 #version c
if re.search( "rsrvd", sigName ) != None :   #version d
   print sigName
   newVal = "%s%s" % ( '0'*signal['bits'],> newVal )
i can use either version a/b the else clause (version c) will not execute.
fortunately,  with version bb, the else clause will execute!!

There must be some other difference in your testing.  I don't have
Python 2.4 available, but I tried your version a in both Python 2.3
and 2.5 using made-up values for sigName, and the else clause is
executed in both.

I went back and tried version a again, blam it is/does work now ?!?!?
I am not sure what changed but version a was the original code that
wouldn't work. All the examples i had read, showed version a as a
working version. I spent significant time trying version a with
parens, spacing changes, different regex values to no avail. hence
the creation of all the other versions.

thanks for your help.
 
C

Chris Angelico

I went back and tried version a again, blam it is/does work now ?!?!?
I am not sure what changed but version a was the original code that
wouldn't work. All the examples i had read, showed version a as a
working version. I spent significant time trying version a with
parens, spacing changes, different regex values to no avail. hence
the creation of all the other versions.

This is why the Short, Self-Contained, Correct Example is so
important. See http://sscce.org/ for some info on that. I often find
myself stuck, begin typing up a post to some appropriate mailing list,
and while coalescing the problem into its smallest possible form, end
up finding the cause directly. More often than not, I end up
discarding the message unsent (though sometimes, I end up submitting a
patch to the language/library maintainers, eg improving the docs so
it's more visible next time). In any case, if you can copy and paste
the exact code and error, it's a lot easier for us to replicate your
problem.

ChrisA
 
K

Kevin T

I agree. Being relatively new to python, i was not sure of quirks so i posted the original code.

I did find the real issue, as I found another loop that was not being executed properly.

It turns out that if the indent started with spaces and ended with tabs, neither eclipse or command line execution would complain. where as if the indent begins with tabs and has spaces in the middle the tools will complain of indentation issues.

i have found that the vi plugin for python is the culprit here. when the plugin does block indentation, the result is indents that begin with spaces. if i disable the vi plugin and use the regular eclipse editor these issues go away.

with other languages i always expand tabs to spaces. the vi plugin does do this properly. if i change all indents to be spaces only will python behave? i inherited a good deal of the code that i am using, which is tab based.

thanks kevin
 
K

Kevin T

I agree. Being relatively new to python, i was not sure of quirks so i posted the original code.

I did find the real issue, as I found another loop that was not being executed properly.

It turns out that if the indent started with spaces and ended with tabs, neither eclipse or command line execution would complain. where as if the indent begins with tabs and has spaces in the middle the tools will complain of indentation issues.

i have found that the vi plugin for python is the culprit here. when the plugin does block indentation, the result is indents that begin with spaces. if i disable the vi plugin and use the regular eclipse editor these issues go away.

with other languages i always expand tabs to spaces. the vi plugin does do this properly. if i change all indents to be spaces only will python behave? i inherited a good deal of the code that i am using, which is tab based.

thanks kevin
 
E

Evan Driscoll

Yes, it's best to use either tabs-only or spaces-only. Quoting from PEP
8 on the subject:

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoking the Python command line interpreter with
the -t option, it issues warnings about code that illegally mixes
tabs and spaces. When using -tt these warnings become errors. These
options are highly recommended!

For new projects, spaces-only are strongly recommended over tabs.
Most editors have features that make this easy to do.


I thought the prohibition against mixing tabs and spaces was made more
strict in Python 3, but I can't find any reference to that now.
Probably I was mistaken.

I'm only entering this thread now so I'm not really in context, but
you're correct; in Python 3, -tt is set by default, which makes illegal
mixing an error.

However, not all mixing is illegal: what it means by "code that
illegally mixes tabs and spaces" is "code whose interpretation differs
depending upon the interpretation of the tab width". While I'm not going
to go test it, I think that if you, say, indent from the first to the
second level with tabs (consistently), indent from the second to third
level with spaces (consistently), and indent from the third to fourth
level with tabs (consistently), it should not complain. Or perhaps I
should say "it should complain that you're a bad person and should feel
bad, but it won't." :) (In fact, you could indent one block at the
second level with tabs and another with spaces.)

Evan


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJQtm81AAoJEAOzoR8eZTzgKs0H/2Cmf7RX2m8DeOniHvR1C3Ni
/4Hf90/ezZmbuYn6Aq+G+obAwuvj4QEzfPyFsz9ENa/RPgyykZ2XymJuxKIO8H/U
4P0rL5gCiHNHEH3EhCAb9DqY7FeSy/JCY6NSOSWL+pyGkjtZ9ut+au54knGvkc4Z
NQlvJgNcxUxazdHSnLdB8SdPLbOXuKgWMnHAEmNpumRBeE3EEf5lA9V5nFWmwwlN
vVbXJJ2j1oa/j8hH6d2u1O1O05ST62F8I4OwJICacx8Uf7V3RtbDDJy9HADyqu2j
zyuk7EIhNB7D6cgmUsxI0m46topwGC6GWNzIWcOXD7uju4boDEpHKIsSe+BYWog=
=MtR+
-----END PGP SIGNATURE-----
 
S

Steven D'Aprano

with other languages i always expand tabs to spaces. the vi plugin does
do this properly. if i change all indents to be spaces only will python
behave? i inherited a good deal of the code that i am using, which is
tab based.

Python will behave correctly if you use all spaces, or all tabs, for
indents. If you mix spaces and tabs, anything can happen.

For this reason, Python 3 is more strict and will raise an explicit error
when it detects mixed spaces/tabs in an indent.

See also the tabnanny tool provided with Python:

[steve@ando ~]$ python -m tabnanny
Usage: /usr/local/lib/python2.7/tabnanny.py [-v] file_or_directory ...
 
S

Steven D'Aprano

I'm only entering this thread now so I'm not really in context, but
you're correct; in Python 3, -tt is set by default, which makes illegal
mixing an error.

However, not all mixing is illegal: what it means by "code that
illegally mixes tabs and spaces" is "code whose interpretation differs
depending upon the interpretation of the tab width". While I'm not going
to go test it, I think that if you, say, indent from the first to the
second level with tabs (consistently), indent from the second to third
level with spaces (consistently), and indent from the third to fourth
level with tabs (consistently), it should not complain.

Correct, which disappoints me. Testing with Python 3:

py> if True:
.... if True: # tab
.... pass # tab, then four spaces
....
py>

I would prefer that the "pass" line would fail with an illegal indent,
but it does not. But at least the following fails cleanly:


py> if True:
.... if True: # tab
.... pass # tab, then four spaces
.... pass # two spaces, tab, four spaces
File "<stdin>", line 4
pass # two spaces, tab, four spaces
^
TabError: inconsistent use of tabs and spaces in indentation

Or perhaps I
should say "it should complain that you're a bad person and should feel
bad, but it won't." :) (In fact, you could indent one block at the
second level with tabs and another with spaces.)

I don't mind different blocks using different indentation. You have
always been able to do this:


py> if True:
.... pass # eight spaces
....
py> if True:
.... pass # two spaces
....
py>

If you don't like that, don't do it! Consistent indentation globally per
file is a matter for coding conventions. However, I think that within a
single block, Python should enforce "all tabs" or "all spaces".

Perhaps it would be nice if Python honoured a directive setting indent
style to spaces or indents, as it honours source code encoding lines:

# -*- indent: <mode> -*-

Where <mode> could be one of:

space Only accept spaces in indentation
tab Only accept tabs in indentation
mixed Accept "mixed" tabs and spaces, but only if consistent

with mixed the default for backward compatibility.
 
D

Dennis Lee Bieber

Correct, which disappoints me. Testing with Python 3:

py> if True:
... if True: # tab
... pass # tab, then four spaces
...
py>

I would prefer that the "pass" line would fail with an illegal indent,
but it does not. But at least the following fails cleanly:


py> if True:
... if True: # tab
... pass # tab, then four spaces
... pass # two spaces, tab, four spaces
File "<stdin>", line 4
pass # two spaces, tab, four spaces
^
TabError: inconsistent use of tabs and spaces in indentation

Unless there has been a major change in the parser... (I still don't
have Python 3.x installed)

I believe <tab> is expanded to 8-spaces -- NOT TO NEXT MULTIPLE OF
8...

So the first is 8+4 => 12 spaces, the second is 2+8+4 => 14 spaces.

Does 2 + <tab> + 2 vs 4 + <tab> vs <tab> + 4 succeed? That would
confirm the treatment.

The main concern with mixed tab and spaces, as I recall, was due to
having /editors/ and /terminals/ configured to show <tab> as a four
space (or anything other than an eight space) increment; so visually
four spaces and one <tab> might look the same... One user might have the
editor showing 4-space indents on <tab> but entering text using 4 spaces
on input -- which now is mis-aligned if the source file HAD <tab> in it.
 
P

Prasad, Ramit

Dennis said:
Unless there has been a major change in the parser... (I still don't
have Python 3.x installed)

I believe <tab> is expanded to 8-spaces -- NOT TO NEXT MULTIPLE OF
8...

A tab is *one* character. Your *editor* may show tabs visually
"expanded" or convert them to spaces. This is entirely editor dependent.
My current (python) editor, doesexpands tabs to the next *multiple* of 4.
It helps keep code aligned, and I have no need for 4 hard spaced tabs
without regards to alignment (yet). I have had editors that did 4 hard
spaced tabs, so it might be a developer/application preference.

... d = f.read()
...
print repr(d)
'\tblah\n test\n\t'
print d[0] + 'goo'
goo
print repr(d[0] + 'goo')
'\tgoo'


So the first is 8+4 => 12 spaces, the second is 2+8+4 => 14 spaces.

Does 2 + <tab> + 2 vs 4 + <tab> vs <tab> + 4 succeed? That would
confirm the treatment.

The main concern with mixed tab and spaces, as I recall, was due to
having /editors/ and /terminals/ configured to show <tab> as a four
space (or anything other than an eight space) increment; so visually
four spaces and one <tab> might look the same... One user might have the
editor showing 4-space indents on <tab> but entering text using 4 spaces
on input -- which now is mis-aligned if the source file HAD <tab> in it.


~Ramit



This emailis confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
 
P

Prasad, Ramit

Ramit said:
Dennis said:
Unless there has been a major change in the parser... (I still don't
have Python 3.x installed)

I believe <tab> is expanded to 8-spaces -- NOT TO NEXT MULTIPLE OF
8...

A tab is *one* character. Your *editor* may show tabs visually
"expanded" or convert them to spaces. This is entirely editor dependent.
My current (python) editor, does expands tabs to the next *multiple* of 4.
It helps keep code aligned, and I have no need for 4 hard spaced tabs
without regards to alignment (yet). I have had editors that did 4 hard
spaced tabs, so it might be a developer/application preference.

... d = f.read()
...
print repr(d)
'\tblah\n test\n\t'
print d[0] + 'goo'
goo
print repr(d[0] + 'goo')
'\tgoo'

Apologies, I missed that it was talking about the parser
and not editor/file. Please disregard my previous post.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top