Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #26007 > unrolled thread

assert expressions

Started byWanderer <wanderer@dialup4less.com>
First post2012-07-24 12:57 -0700
Last post2012-07-24 14:25 -0700
Articles 7 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  assert expressions Wanderer <wanderer@dialup4less.com> - 2012-07-24 12:57 -0700
    Re: assert expressions Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-24 14:31 -0600
      Re: assert expressions Wanderer <wanderer@dialup4less.com> - 2012-07-24 13:47 -0700
        Re: assert expressions Wanderer <wanderer@dialup4less.com> - 2012-07-24 13:56 -0700
      Re: assert expressions Wanderer <wanderer@dialup4less.com> - 2012-07-24 13:44 -0700
        Re: assert expressions Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-24 15:22 -0600
          Re: assert expressions Wanderer <wanderer@dialup4less.com> - 2012-07-24 14:25 -0700

#26007 — assert expressions

FromWanderer <wanderer@dialup4less.com>
Date2012-07-24 12:57 -0700
Subjectassert expressions
Message-ID<9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com>
If I use the code 

assert False, "unhandled option"

I get output like:

option -q not recognized
for help use --help

What other expressions can I use other than "unhandled option"? Is there a list somewhere?

Thanks

[toc] | [next] | [standalone]


#26009

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-07-24 14:31 -0600
Message-ID<mailman.2553.1343161917.4697.python-list@python.org>
In reply to#26007
On Tue, Jul 24, 2012 at 1:57 PM, Wanderer <wanderer@dialup4less.com> wrote:
> If I use the code
>
> assert False, "unhandled option"
>
> I get output like:
>
> option -q not recognized
> for help use --help
>
> What other expressions can I use other than "unhandled option"? Is there a list somewhere?

Are you using argparse or optparse or getopt or something else
altogether?  And where are you placing this assert?  It would be
helpful to see some actual code to understand what you are doing.

And by the way, assert is a very bad way to check user input or to
unconditionally raise an exception.  The reason is that if Python is
invoked with -O, then all assertions are removed from the compiled
bytecode, and then your unconditional exception code doesn't raise any
exception at all.  If you want to raise an exception, just do it:

raise Exception("unhandled option")

Ideally, you would also subclass Exception to create a more specific
exception class for your custom exception:

class UnhandledOptionException(Exception):
    pass

# Then, later on...

raise UnhandledOptionException("-q")

[toc] | [prev] | [next] | [standalone]


#26010

FromWanderer <wanderer@dialup4less.com>
Date2012-07-24 13:47 -0700
Message-ID<8cac515d-fb79-4043-8df0-8d54335a00fb@j4g2000yqj.googlegroups.com>
In reply to#26009
On Jul 24, 4:31 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Tue, Jul 24, 2012 at 1:57 PM, Wanderer <wande...@dialup4less.com> wrote:
> > If I use the code
>
> > assert False, "unhandled option"
>
> > I get output like:
>
> > option -q not recognized
> > for help use --help
>
> > What other expressions can I use other than "unhandled option"? Is there a list somewhere?
>
> Are you using argparse or optparse or getopt or something else
> altogether?  And where are you placing this assert?  It would be
> helpful to see some actual code to understand what you are doing.
>
> And by the way, assert is a very bad way to check user input or to
> unconditionally raise an exception.  The reason is that if Python is
> invoked with -O, then all assertions are removed from the compiled
> bytecode, and then your unconditional exception code doesn't raise any
> exception at all.  If you want to raise an exception, just do it:
>
> raise Exception("unhandled option")
>
> Ideally, you would also subclass Exception to create a more specific
> exception class for your custom exception:
>
> class UnhandledOptionException(Exception):
>     pass
>
> # Then, later on...
>
> raise UnhandledOptionException("-q")

I left out the Usage class

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

[toc] | [prev] | [next] | [standalone]


#26011

FromWanderer <wanderer@dialup4less.com>
Date2012-07-24 13:56 -0700
Message-ID<68944ec3-e6c3-4623-ac83-8ab35a14124a@u2g2000yqj.googlegroups.com>
In reply to#26010
On Jul 24, 4:47 pm, Wanderer <wande...@dialup4less.com> wrote:
> On Jul 24, 4:31 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote:
>
>
>
>
>
>
>
>
>
> > On Tue, Jul 24, 2012 at 1:57 PM, Wanderer <wande...@dialup4less.com> wrote:
> > > If I use the code
>
> > > assert False, "unhandled option"
>
> > > I get output like:
>
> > > option -q not recognized
> > > for help use --help
>
> > > What other expressions can I use other than "unhandled option"? Is there a list somewhere?
>
> > Are you using argparse or optparse or getopt or something else
> > altogether?  And where are you placing this assert?  It would be
> > helpful to see some actual code to understand what you are doing.
>
> > And by the way, assert is a very bad way to check user input or to
> > unconditionally raise an exception.  The reason is that if Python is
> > invoked with -O, then all assertions are removed from the compiled
> > bytecode, and then your unconditional exception code doesn't raise any
> > exception at all.  If you want to raise an exception, just do it:
>
> > raise Exception("unhandled option")
>
> > Ideally, you would also subclass Exception to create a more specific
> > exception class for your custom exception:
>
> > class UnhandledOptionException(Exception):
> >     pass
>
> > # Then, later on...
>
> > raise UnhandledOptionException("-q")
>
> I left out the Usage class
>
> class Usage(Exception):
>     def __init__(self, msg):
>         self.msg = msg

I seem to be missing a post.

Here is the code.

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):

    help_message = \
    ("\nOtFixture.py:\n Set the Optics Test Fixture Light Source Light
Level\n" +
     "Options:\n"
     "  -l, --level= <The light level percent of Max: 0.0 to 100.0>\n"
+
     "  -v, --verbose: Print messages to the terminal.\n"
     "  -h, --help: This message\n")

    level = None
    verbose = False
    helpflag = False

    options = "hl:v"
    long_options = ["help","level=","verbose"]
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, _args = getopt.getopt(argv[1:],
options,long_options)
        except getopt.error, msg:
            raise Usage(msg)

        for o, a in opts:
            if o in ("-h", "--help"):
                print help_message
                helpflag = True
            elif o in ("-l", "--level"):
                level = a
            elif o in ("-v", "--verbose"):
                verbose = True
            else:
                assert False, "unhandled option"

        if not helpflag:
            if level == None:
                level = raw_input("Enter the light level from 0.0 to
100.0%: ")
            if level.replace(".", "", 1).isdigit():
                level = float(level)
            else:
                msg = "\n" + str(level) + " is not a number.\n"
                raise Usage(msg)

        if verbose and level is not None:
            print "The level is ", level, " percent"

        if level is not None:
            if 0.0 <= level <= 100.0:
                ot = OtFixture(verbose)
                ot.setLightLevel(level)
                print "Light Level set to ", level,"%."
            else:
                msg = "\n" + str(level) + " is not in the range 0.0 to
100.0%\n"
                raise Usage(msg)


    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())

I don't really have a problem. I'm was just curious.

How do you invoke python -O? When I run python.exe -O OtFixture.py -q,
I get the same response. It's a capital letter O, right?

[toc] | [prev] | [next] | [standalone]


#26012

FromWanderer <wanderer@dialup4less.com>
Date2012-07-24 13:44 -0700
Message-ID<8c5da998-e428-4000-adba-f5eee86ac971@d32g2000yqn.googlegroups.com>
In reply to#26009
On Jul 24, 4:31 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Tue, Jul 24, 2012 at 1:57 PM, Wanderer <wande...@dialup4less.com> wrote:
> > If I use the code
>
> > assert False, "unhandled option"
>
> > I get output like:
>
> > option -q not recognized
> > for help use --help
>
> > What other expressions can I use other than "unhandled option"? Is there a list somewhere?
>
> Are you using argparse or optparse or getopt or something else
> altogether?  And where are you placing this assert?  It would be
> helpful to see some actual code to understand what you are doing.
>
> And by the way, assert is a very bad way to check user input or to
> unconditionally raise an exception.  The reason is that if Python is
> invoked with -O, then all assertions are removed from the compiled
> bytecode, and then your unconditional exception code doesn't raise any
> exception at all.  If you want to raise an exception, just do it:
>
> raise Exception("unhandled option")
>
> Ideally, you would also subclass Exception to create a more specific
> exception class for your custom exception:
>
> class UnhandledOptionException(Exception):
>     pass
>
> # Then, later on...
>
> raise UnhandledOptionException("-q")

I'm using getopt but not at that point. I really don't have a problem.
I'm just curious. I've never seen anything else after
assert False,

Here is some code.

def main(argv=None):

    help_message = \
    ("\nOtFixture.py:\n Set the Optics Test Fixture Light Source Light
Level\n" +
     "Options:\n"
     "  -l, --level= <The light level percent of Max: 0.0 to 100.0>\n"
+
     "  -v, --verbose: Print messages to the terminal.\n"
     "  -h, --help: This message\n")

    level = None
    verbose = False
    helpflag = False

    options = "hl:v"
    long_options = ["help","level=","verbose"]
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, _args = getopt.getopt(argv[1:],
options,long_options)
        except getopt.error, msg:
            raise Usage(msg)

        for o, a in opts:
            if o in ("-h", "--help"):
                print help_message
                helpflag = True
            elif o in ("-l", "--level"):
                level = a
            elif o in ("-v", "--verbose"):
                verbose = True
            else:
                assert False, "unhandled option"

        if not helpflag:
            if level == None:
                level = raw_input("Enter the light level from 0.0 to
100.0%: ")
            if level.replace(".", "", 1).isdigit():
                level = float(level)
            else:
                msg = "\n" + str(level) + " is not a number.\n"
                raise Usage(msg)

        if verbose and level is not None:
            print "The level is ", level, " percent"

        if level is not None:
            if 0.0 <= level <= 100.0:
                ot = OtFixture(verbose)
                ot.setLightLevel(level)
                print "Light Level set to ", level,"%."
            else:
                msg = "\n" + str(level) + " is not in the range 0.0 to
100.0%\n"
                raise Usage(msg)


    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())


[toc] | [prev] | [next] | [standalone]


#26013

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-07-24 15:22 -0600
Message-ID<mailman.2554.1343165006.4697.python-list@python.org>
In reply to#26012
On Tue, Jul 24, 2012 at 2:44 PM, Wanderer <wanderer@dialup4less.com> wrote:
> I'm using getopt but not at that point. I really don't have a problem.
> I'm just curious. I've never seen anything else after
> assert False,
>
> Here is some code.

It doesn't matter what you put after the assert False, because that
line is not actually reached.  When getopt sees the -q, it immediately
raises a getopt.error, which you catch and then immediately reraise as
a Usage exception, which is then caught and printed at the end.  The
chained ifs with the assert statement never even execute in this
scenario.

Seeing the assert in context, it makes more sense.  It's not
intercepting some unimplemented option and preventing the program from
proceeding; it's there as a development tool to catch programming
errors where an option is added to the getopt configuration but is not
implemented in the if chain.

[toc] | [prev] | [next] | [standalone]


#26014

FromWanderer <wanderer@dialup4less.com>
Date2012-07-24 14:25 -0700
Message-ID<1ebab0bd-f302-47e2-b125-3da9f9deeb38@y12g2000yqe.googlegroups.com>
In reply to#26013
On Jul 24, 5:22 pm, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Tue, Jul 24, 2012 at 2:44 PM, Wanderer <wande...@dialup4less.com> wrote:
> > I'm using getopt but not at that point. I really don't have a problem.
> > I'm just curious. I've never seen anything else after
> > assert False,
>
> > Here is some code.
>
> It doesn't matter what you put after the assert False, because that
> line is not actually reached.  When getopt sees the -q, it immediately
> raises a getopt.error, which you catch and then immediately reraise as
> a Usage exception, which is then caught and printed at the end.  The
> chained ifs with the assert statement never even execute in this
> scenario.
>
> Seeing the assert in context, it makes more sense.  It's not
> intercepting some unimplemented option and preventing the program from
> proceeding; it's there as a development tool to catch programming
> errors where an option is added to the getopt configuration but is not
> implemented in the if chain.

Thanks. Now it makes more sense.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web