How to structure Python code for fewer headaches

Status
Not open for further replies.

DavlinLotze

Ars Scholae Palatinae
830
My knowledge of Python and of programming in general is self-taught from online sources - just enough to make me dangerous.

I'm working on my first major Python project, and it's going well in some ways, but when my initial file reached 1000 lines, I decided I needed to break it up into different files (er.. "modules"). So now it's in 5 modules divided up by subject - sort of. The smallest is 49 lines - the "main" file is still 960, which is still on the verge of being unwieldy. But my primary question is about classes and constants defined in them.

In the interest of a made-up example, this is how I would like to use Python:
Code:
class HappyFastMenu(object):

    class VomitError(Exception):
        pass

    OMNIVORE = object()
    CATHOLIC = object()

    # structure offsets
    DRINK = 0
    VEGETABLE = 1
    MEAT = 2

    def GetMeal(self, expensive):
        r = ["Nothing" for i in xrange(3)]
        r[VEGETABLE] = WhatsInSeason()
        if expensive:
            r[DRINK] = "Wine"
            r[MEAT] = "Steak"
        else:
            r[DRINK] = "Water"
            r[MEAT] = "Canned sardines"
        return r

    class MealListAquisition(object):

        # flags
        Finished = 1
        GoWild = 2
        FridayFish = 4

        def __init__(self, themenu, opts, kind=OMNIVORE):
            self.flags = 0
            if "Money is no object" in opts:
                self.flags |= GoWild
            if id(kind) == id(CATHOLIC):
                self.flags |= FridayFish
            self.obj = themenu
            self.state = []

        def ProcessNext(self):
            if len(self.state) < 7:
                meal = self.obj.GetMeal(self.flags & GoWild )
                if meal[VEGETABLE] == "Artichokes" and meal[DRINK] == "Pepsi":
                    raise VomitError("That's no good!", meal)
                self.state.append(meal)
            else:
                self.flags |= Finished

        def IsDone(self):
            return self.flags & Finished
        def Result(self):
            pass

BobsMenu = HappyFastMenu()
meals_aqu = HappyFastMenu.MealListAquisition(BobsMenu, [])
while not meals_aqu.IsDone():
    meals_aqu.ProcessNext()
BobsMeals = meals_aqu.Result()

But instead it turns into something nasty like:
Code:
class HappyFastMenu(object):

    class VomitError(Exception):
        pass

    OMNIVORE = object()
    CATHOLIC = object()

    # structure offsets
    DRINK = 0
    VEGETABLE = 1
    MEAT = 2

    def GetMeal(self, expensive):
        cls = HappyFastMenu
        r = ["Nothing" for i in xrange(3)]
        r[cls.VEGETABLE] = WhatsInSeason()
        if expensive:
            r[cls.DRINK] = "Wine"
            r[cls.MEAT] = "Steak"
        else:
            r[cls.DRINK] = "Water"
            r[cls.MEAT] = "Canned sardines"
        return r

    class MealListAquisition(object):

        # flags
        Finished = 1
        GoWild = 2
        FridayFish = 4

        def __init__(self, themenu, opts, kind=???): # How to get OMNIVORE?
            cls = HappyFastMenu.MealListAquisition
            supercls = HappyFastMenu
            self.flags = 0
            if "Money is no object" in opts:
                self.flags |= cls.GoWild
            if id(kind) == id(supercls.CATHOLIC):
                self.flags |= cls.FridayFish
            self.obj = themenu
            self.state = []

        def ProcessNext(self):
            cls = HappyFastMenu.MealListAquisition
            supercls = HappyFastMenu
            if len(self.state) < 7:
                meal = self.obj.GetMeal(self.flags & cls.GoWild )
                if meal[supercls.VEGETABLE] == "Artichokes" and meal[supercls.DRINK] == "Pepsi":
                    raise supercls.VomitError("That's no good!", meal)
                self.state.append(meal)
            else:
                self.flags |= cls.Finished

        def IsDone(self):
            return self.flags & HappyFastMenu.MealListAquisition.Finished
        def Result(self):
            pass

BobsMenu = HappyFastMenu()
meals_aqu = HappyFastMenu.MealListAquisition(BobsMenu, [])
while not meals_aqu.IsDone():
    meals_aqu.ProcessNext()
BobsMeals = meals_aqu.Result()

Obviously I just don't get it and I'm doing it wrong. Help! Thanks.
 

Binary Alchemy

Ars Centurion
260
Subscriptor
Code:
    OMNIVORE = object()
    CATHOLIC = object()

    # structure offsets
    DRINK = 0
    VEGETABLE = 1
    MEAT = 2
This buys you nothing, just use strings.
Code:
HappyFastMenu.MealListAquisition
There's no reason to embed MealListAquisition in HappyFastMenu, this is probably part of what's making it hard to break things into modules.

A saner version:
Code:
class VomitError(Exception):
    pass

class HappyFastMenu(object):
    def GetMeal(self, expensive):
        result = dict()
        result["vegetable"] = WhatsInSeason()
        if expensive:
            result["drink"] = "Wine"
            result["meat"]  = "Steak"
        else:
            result["drink"] = "Water"
            result["meat"] = "Canned sardines"
        return result

class MealListAquisition(object):
    def __init__(self, themenu, opts, kind="omnivore"):
        self.go_wild = False
        self.fish_friday = False
        self.done = False
    
        if "Money is no object" in opts:
            self.go_wild = True
        if kind == "catholic":
            self.fish_friday = True
        self.obj = themenu

    def ProcessNext(self):
        if len(self.state) < 7:
            meal = self.obj.GetMeal(self.go_wild)
            if meal["vegetable"] == "Artichokes" and meal["drink"] == "Pepsi":
                raise VomitError("That's no good!", meal)
            self.state.append(meal)
        else:
            self.done = True

    def Result(self):
        return self.state

BobsMenu = HappyFastMenu()
meals_aqu = MealListAquisition(BobsMenu, [])
while not meals_aqu.done:
    meals_aqu.ProcessNext()
BobsMeals = meals_aqu.Result()

I kept MealListAquisition because I assume it does something more complex in your real code. If it's only used to generate the list in meals_aqu.state then make it a function rather than a class.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
You'd get more useful help if you'd explain what you're trying to accomplish and what problem you're trying to solve. It's hard to meaningfully restructure code without context.

Valid uses for nested classes in Python are rare. I think you're confused about how class structures work in Python too, since you call the outer class a super class in the code. I would remove the nesting alltogether, it's entirely unnecessary.

Iterators should follow the iteration protocol and implement __iter__ and next. Ideally, you should just use a generator and I don't see why you couldn't do that here.

Valid uses of flags in Python is quite rare.

I implemented a version of what I think you want in about 32 lines. I can post it if you want, but it's so radically different I'm not sure posting it is all that helpful. I'll give you a mess of hints though and see if that sets you on the right path:
  • You don't need to create your own classes here, beyond the exception. You can use collections.namedtuple to create small record classes, allowing you to store single meal (meat, fish, veggie).
  • You need to distinguish which items are expensive. One way to do this is to used a namedtuple again. If you do this, you can use a list comprehension to filter out expensive and non-expensive items. Another approach is to keep separate lists of expensive and inexpensive items. koala gave a helpful hint if you go this route.
  • It may be helpful to separate fish from other meat, to handle fish Fridays
  • The random module can generate random numbers to generate unique meals.
  • Don't use flags, but separate booleans for expensive v. inexpensive and fish Friday vs. other days
  • Use a generator to return many meals. Look at the itertools module for a quick overview, and documentation online about them.
  • Since there's a vegetable of the day, it should be the same for every meal.
Hopefully that will set you on the right path. If you want the code I'll be happy to post it, but I think the journey is more important than the answer here.
 

DavlinLotze

Ars Scholae Palatinae
830
LordHunter317":320yclg6 said:
I think you're confused about how class structures work in Python too, since you call the outer class a super class in the code.
Oh, right - yeah, I understand that, but I wasn't thinking straight when I named the variables. "supercls" should be "outercls"

LordHunter317":320yclg6 said:
Valid uses of flags in Python is quite rare. ... Don't use flags, but separate booleans
I can see how that would simplify some things, depending on the situation. But it would complicate matters if you want to be able to say:
Code:
CertainValue = ThisFlag + ThatFlag + AnotherFlag
...
if self.flags == CertainValue:
    ...
Also, I'm using Python as a means to prototype a program that would be reimplemented in a faster language in a case where speed and memory use matters, so I don't want my Python logic and object structure to look a lot different from how it would be implemented in the other language.

LordHunter317":320yclg6 said:
Iterators should follow the iteration protocol and implement __iter__ and next. Ideally, you should just use a generator and I don't see why you couldn't do that here.
I'll have to think about that some more. In my actual code, I'm trying to implement a serializer and deserializer for a container class - let's call it "Complex". Serializing Complex is a different thing from iterating through its contents.

LordHunter317":320yclg6 said:
Valid uses for nested classes in Python are rare. I would remove the nesting altogether, it's entirely unnecessary.
Binary Alchemy":320yclg6 said:
There's no reason to embed...
LordHunter317":320yclg6 said:
You'd get more useful help if you'd explain what you're trying to accomplish
Okay, let's ignore the original example for now. It was a silly example and only as clear as my head was with too-little sleep. The main thing I was intending to indicate is that I've been using class variables and class methods defined inside the class, but they seem to be a PITA to access in any instance methods, and perhaps impossible to use as method argument defaults. (I couldn't figure out how, anyway.) The Serialization is the only class I've tried to embed/nest so far, though it was tempting to do it on others. Let me see if I can convey better why I was wanting to nest this class, and then you can explain how to better achieve my goals. My original thought was to implement the interface like this:
Code:
class Complex:
    class Serialization:
        def __init__(self, obj):
            self.objstack = [obj]
            ...
    def NewSerialization(self):
        return Serialization(self)

comp = Complex()
...
comp_ser = comp.NewSerialization()

If you take Serialization out of Complex, e.g.
Code:
class ComplexSerialization:
    def __init__(self, obj):
        self.objstack = [obj]
        ...

class Complex:
    def Serialization(self):
        return ComplexSerialization(self)

...
comp = Complex()
...
comp_ser = comp.Serialization()
This seems less organized, to me. To me, having to call the class name "ComplexSerialization" instead of "Complex.Serialization" or "comp.Serialization" is less fun.
Also, "Serialization" has everything to do with "Complex" - it's no good without the class "Complex". More importantly, "Serialization" is designed to access unexposed symbols (if there is such a thing in Python; what I mean is symbols not designed to be part of the public interface of "Complex"). So if someone is working on the class (yeah, I know, that would be me - I'm just saying...) and doesn't change any of the public interface of "Complex", but does change some internal things, he could break "ComplexSerialization" if he doesn't know or remember that ComplexSerialization accesses these non-public attributes, methods, etc. of "Complex".

You can use collections.namedtuple
Yeah, that might help - thanks.

Here's a slightly expanded example of "Complex". It obviously doesn't work like this, but this is how I imagine it working.
"OPEN" is a unique placeholder used by both Serialization and Deserialization, thus why it is defined in Complex.
Code:
class Complex:
    OPEN = object()
    class Serialization:
        READY_FOR_OPEN = -1
        def __init__(self, obj):
            self.objstack = [obj]
            self.indstack = [READY_FOR_OPEN]
        def isDone(self):
            return len(self.indstack) == 0
        CONSUME_ALL = -1
        def Consume(self, n=CONSUME_ALL):
            r = []
            ...
            return r
        def NewSerialization(self):
            return Serialization(self)
    class Deserialization:
        def Feed(self, items):
            for i in items:
                if id(i) == id(OPEN):
                    ...
...
comp = Complex()
...
comp_ser = comp.NewSerialization()
ser_first_50 = comp_ser.Consume(50)
ser_next_50 = comp_ser.Consume(50)
if not comp_ser.isDone():
    ser_remaining = comp_ser.Consume()
 

Binary Alchemy

Ars Centurion
260
Subscriptor
Your code is cumbersome because you're trying to write Java-in-Python or C-in-Python, don't do that.

Not Pythonic:
Code:
CertainValue = ThisFlag + ThatFlag + AnotherFlag
...
if self.flags == CertainValue:
    ...

Pythonic:
Code:
self.this_flag  = True
self.that_flag  = False
self.other_flag = True
...
if self.this_flag and not self.that_flag and self.other_flag:
    ...


Code:
class Complex:
    class Serialization:
Stop embedding classes! Just don't do it, this is not Java, it is never* appropriate to do this in Python. If you need to organize things put them in modules.

class variables and class methods
You should never* use a "class method" in python except as an alternate constructor, even then it's optional. If something doesn't act on the self variable it should be a freestanding function. If you need to define constants referred to by more than one class define them at the module level, not in a class.


* "never" subject to extenuating circumstances, you are nowhere near those circumstances.
 

ahankinson

Wise, Aged Ars Veteran
117
Whoa. If I came across Python like yours, I would probably go postal.

Code:
class Complex(object):
    def __init__(self):
        self.obj_list = []

    def consume(self, list_of_consumables):
        for obj in list_of_consumables:
            self.obj_list.append(SerializedObject(obj))

    def barf(self, n=0):
        if not isinstance(n, int):
            raise ArgumentMustBeAnIntegerDummyError()
        if n == 0 or n :
            return [r.deserialized for r in self.obj_list]
        else:
            return [r.deserialized for r in self.obj_list[:n]]

    def poop(self, n=0):
        if not isinstance(n, int):
            raise ArgumentMustBeAnIntegerDummyError()
        if n == 0 or n :
            return [r for r in self.obj_list]
        else:
            return [r for r in self.obj_list[:n]]


class SerializedObject(object):
    def __init__(self, object_to_serialize):
        self.raw_object = object_to_serialize
        self._serialize()

    @property
    def deserialized(self):
        return raw_object

    def _serialize(self):
        # do whatever you want to do here to make this a serialized object
        ... process self.raw_object ...



...
comp = Complex()
comp.consume(a_bunch_of_raw_objects)  # wraps a bunch of raw objects in your complex class
comp.barf()  # returns all deserialized raw objects
comp.barf(n=50)  # returns the first 50 deserialized objects
comp.poop()  # returns all serialized objects
comp.poop(n=50)  # returns the first 50 serialized objects

For even more magic you can look at implementing __iter__(), next(), __getitem__(), __len__(), and a couple other container methods.

Edit: made the example a bit more pythonic
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":2g47oonq said:
LordHunter317":2g47oonq said:
Valid uses of flags in Python is quite rare. ... Don't use flags, but separate booleans
I can see how that would simplify some things, depending on the situation. But it would complicate matters if you want to be able to say:
Code:
CertainValue = ThisFlag + ThatFlag + AnotherFlag
...
if self.flags == CertainValue:
    ...
Not really. You've just moved the complexity, not removed it. But it doesn't really matter.

Also, I'm using Python as a means to prototype a program that would be reimplemented in a faster language in a case where speed and memory use matters, so I don't want my Python logic and object structure to look a lot different from how it would be implemented in the other language.
Then you probably shouldn't write your prototype in Python. Idiomatic Python is going to look too radically different than whatever language you have in mine, I imagine. Even where concepts are shared (e.g., iteration, collections), the Python implementation tends to be quite different.

There are some situations where the Python code resembles what you write in other languages, such as matrix math. File processing is emphatically not one of those situations.

The main thing I was intending to indicate is that I've been using class variables and class methods defined inside the class,
This is frequently not ideal in any OOP language, but is basically a bad thing in Python. Classes should almost never have any data attributes. Data attributes generally exist only on instances (self).

Also, 'class method' has a specific meaning in Python indicated by @classmethod, and it doesn't have a good equivalent in many other OOP languages. It doesn't mean what you've implied here.

but they seem to be a PITA to access in any instance methods, and perhaps impossible to use as method argument defaults. (I couldn't figure out how, anyway.)
You access them like any other qualified name; they're not special in any way shape or form, beyond the fact that accesses must always be qualified.

You can also access them through 'self', but assignment creates that name on the instance, so future reads are accessing a different variable. This is how you usually access methods[1]: Pyhton first looks on the instance (self), then looks on the class.

This seems less organized, to me. To me, having to call the class name "ComplexSerialization" instead of "Complex.Serialization" or "comp.Serialization" is less fun.
So just call it Serialization. There's no reason not to do so. You have modules to scope your names, so use them.

Also, "Serialization" has everything to do with "Complex" - it's no good without the class "Complex". More importantly, "Serialization" is designed to access unexposed symbols (if there is such a thing in Python; what I mean is symbols not designed to be part of the public interface of "Complex").
Generally, this means you're approaching your encapsulation incorrectly. The right approach is generally:
Code:
class Serializer(object):
    def __init__(self, secret1, secret2, secret3):
         self.secret1 = secret1 # Rest as exercise
    
    def serialize(self, file):
         file.write(self.secret1) # Rest as exercise

class Complex(object):
    def __init__(self):
         self.secret1 = 42 

    def serializer(self):
         return Serializer(self.secret1, 55, 47)
Clean, consistent, and reasonably coupled.

[1] Ignoring the many special cases.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":3qtsjs51 said:
LordHunter317":3qtsjs51 said:
Iterators should follow the iteration protocol and implement __iter__ and next. Ideally, you should just use a generator and I don't see why you couldn't do that here.
I'll have to think about that some more. In my actual code, I'm trying to implement a serializer and deserializer for a container class - let's call it "Complex". Serializing Complex is a different thing from iterating through its contents.
I didn't respond to this last night, but this code:
Code:
comp_ser = comp.NewSerialization()
ser_first_50 = comp_ser.Consume(50)
ser_next_50 = comp_ser.Consume(50)
if not comp_ser.isDone():
    ser_remaining = comp_ser.Consume()
is iteration of a sort, hence there's a good chance the serializer should be an iterator.

Iteration is a general technique to consume any sequence of objects. The objects need not be stored in a collection, look at some of the generators stored inside itertools!
 

DavlinLotze

Ars Scholae Palatinae
830
Just an update. I do appreciate all the comments on how to be more Pythonic, and I've taken some of them to heart. But not all. Since this is my project, and I can do things my way, and since Python is so flexible, I made use of its flexibility. I wrote a module that gives me the option of nesting classes to any depth without any extra indentation. Anywhere in a class's methods, I can refer to the class with the identifier "c", or to the enclosing class, if there is one, with "outer". (So I don't really have a use for the @classmethod decorator anymore, unless I'm missing something else it provides.) Functions/methods can also refer to themselves with the identifier "this_func", which can come in handy. It took a little while to work out, but it taught me some valuable things about Python, too. The "preprocessor", if you can call it that, also provides full logging which is printed when it encounters a problem, or by optionally excluding the log object from being deleted by the cleanup routine.

I've used it in about half my modules so far, and I'm happy with it. I'm also trying to get used to using exceptions properly instead of error codes, etc. The one thing I don't like about the try/except approach is that I don't have a good way of determining if the exception was raised by the function I just called, or if it was raised by a function that it called, or by recursion, etc. Also, except * as err: doesn't work - are you just supposed to say except BaseException as err:?

I split my biggest file last night, so the largest file is only about 540 lines right now. Pretty soon I'll start adding GUI display for various things. I haven't yet committed myself to a particular toolkit, so if you have any experience with them and have suggestions, I'm all ears. I'm probably going to use Tkinter, PyGTK, or PyQt. I was interested in wxPython earlier, but I found it to have serious redraw issues when I tried it various times.
 

technophile

Ars Legatus Legionis
23,768
DavlinLotze":3tfmmmur said:
The one thing I don't like about the try/except approach is that I don't have a good way of determining if the exception was raised by the function I just called, or if it was raised by a function that it called, or by recursion, etc.
The one thing I don't like about this sentence is that I can't figure out why you care.



Also, given what Alamout quoted, I'm fairly certain that in about 6-12 months you are going to get top billing on thedailywtf.com for a solid week.
 

DavlinLotze

Ars Scholae Palatinae
830
To give you a basic skeleton of how it works:
Code:
from myhelpermodule import *
exec mhm_init

Import("anothermodule", "eggs Cheese.Blue:BlueCheese toast")

Class("MyThing")

Import("foo", "Bar", pinunder="c")

MyConstant = something()

def __init__(self):
 pass

Class("Builder")

Class("Error", "Exception", """This is the documentation for
the Error class.""")
EndClass()

@staticmethod
def DoSomething(spam):
 if spam is A_Problem:
  raise c.Error("Problem in '%s'." % this_func.__name__)

EndClass()

EndClass()

Cleanup()

I'm not trying to convince anyone that it's a great idea - I'm just explaining what I did, and that I'm very pleased with the way it allows me to arrange my code.

technophile":2zhuxx7u said:
The one thing I don't like about this sentence is that I can't figure out why you care.
As one silly example, I may want to do something like:
Code:
inp = getInput()
try:
 doSomething(inp)
except TypeError:
 print "Sorry, your input is garbage."
I definitely don't want to catch any TypeError except one raised by doSomething in direct response to my input. If it's a TypeError somewhere down the line, I want it to kill my program because it means my program is buggy. If I accidentally catch such an exception, I miss the bug.
 
D

Deleted member 43669

Guest
Exceptions are for exceptional cases. Invalid user input is often dealt with exceptions in a lot of frameworks, but I don't think it's the right way to do it (unless there's another layer of validation in front of you and invalid input can only reach you in exceptional cases).

Although this might be the subject for a different thread.

...

Also, unless you are writing Lisp or something, it's highly unlikely that "changing" the way the language you use works is the right thing to do. It's great fun for experimenting, but if someone else is going to touch your code, don't do it.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":9v7wj90d said:
I wrote a module that gives me the option of nesting classes to any depth without any extra indentation.
Bad idea, because nesting classes is a bad idea. I'm not sure why you have such a love affair with them, but a break-up would do you lots of good.

Anywhere in a class's methods, I can refer to the class with the identifier "c", or to the enclosing class, if there is one, with "outer".
I don't know how you can do this thread-safely without lots of extra work.

(So I don't really have a use for the @classmethod decorator anymore, unless I'm missing something else it provides.)
What is the value of 'c' when calling a function defined on a parent class?

Functions/methods can also refer to themselves with the identifier "this_func", which can come in handy.
I can't think of many, really any, valid reasons for this.

It took a little while to work out, but it taught me some valuable things about Python, too. The "preprocessor", if you can call it that, also provides full logging which is printed when it encounters a problem, or by optionally excluding the log object from being deleted by the cleanup routine.
There is no preprocessor. There's just the Python interpreter, which processes your Python files. Python's execution model allows for arbitrary statements at the top level, hence you can run arbitrary code when importing an module.

The one thing I don't like about the try/except approach is that I don't have a good way of determining if the exception was raised by the function I just called, or if it was raised by a function that it called, or by recursion, etc.
You're not supposed to care. Code that does care is almost certainly structurally and logically wrong.

Also, except * as err: doesn't work - are you just supposed to say except BaseException as err:?
Probably just 'except' but it depends on the specifics.


Look, you've done a lot of work here, but all the work is to enable things that you shouldn't care about in the first place. Your code would almost certainly be a lot smaller, a lot simpler, and a lot faster if you stopped worrying about all of these things. At least, you should tell us why you care, as it's symptomatic of serious design issues.
 

agifford

Ars Tribunus Militum
2,142
LordHunter317":10pw7feo said:
DavlinLotze":10pw7feo said:
Also, except * as err: doesn't work - are you just supposed to say except BaseException as err:?
Probably just 'except' but it depends on the specifics.

Don't use except: or except BaseException, unless you really intend that, it will catch exceptions you shouldn't be catching, like KeyboardInterrupt & SystemExit. Instead except Exception:. Alternately, if you do catch everything, be sure to re-raise at the end (if you wanted to log the SystemExit, for example).

In the docs for the exception hierarchy you can see that the errors you should be caring about extend from Exception or StandardError http://docs.python.org/2/library/exceptions.html#exception-hierarchy
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
In the situations where 'except:' is appropriate (e.g., transaction rollback), it would be generally incorrect to exclude exceptions "you shouldn't be catching". Put another way, if a bare except is bad, then 'finally' should also be banned as well. If you support the use of finally, you must also support the use of bare except.

It's also perfectly cromulent, and frequently a good idea in CLI applications, to catch KeyboardInterrupt. Daemons too. Anytime you'd handle SIGINT, there's a good chance the right way to do it is to catch KeyboardInterrupt.
 

Alamout

Ars Legatus Legionis
27,285
LordHunter317":2md3ybxo said:
There is no preprocessor. There's just the Python interpreter, which processes your Python files. Python's execution model allows for arbitrary statements at the top level, hence you can run arbitrary code when importing an module.
He's calling his code the "preprocessor". The module that somehow undoes all the insanity and turns it into valid--if not advisable--Python.

Twisting a new language to work the way you want to use it is Wrong™. You'll be much better off if you just learn how to use the language correctly.
 
DavlinLotze":k15peoyo said:
I definitely don't want to catch any TypeError except one raised by doSomething in direct response to my input. If it's a TypeError somewhere down the line, I want it to kill my program because it means my program is buggy. If I accidentally catch such an exception, I miss the bug.

I'm not a Python wizard, but couldn't you handle this with a custom exception? Define a class
Code:
class DoSomethingException(Exception}:
and raise it in your doSomething method.

Let me know if this is the Wrong Way to do things.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":mx867xmq said:
As one silly example, I may want to do something like:
Code:
inp = getInput()
try:
 doSomething(inp)
except TypeError:
 print "Sorry, your input is garbage."
I definitely don't want to catch any TypeError except one raised by doSomething in direct response to my input.
And normal exception handling lets you do that just fine. You don't need to know:
The one thing I don't like about the try/except approach is that I don't have a good way of determining if the exception was raised by the function I just called, or if it was raised by a function that it called, or by recursion, etc.
In order to do that.

If it's a TypeError somewhere down the line, I want it to kill my program because it means my program is buggy. If I accidentally catch such an exception, I miss the bug.
No, you cannot assume that a TypeError raised by a function called by 'doSomething' ipso-facto means there is a bug in your application. Either you can handle a TypeError raised from doSomething or you can't. If you can, write a correct exception handler. If you can't, then you shouldn't write one at all.
 

DavlinLotze

Ars Scholae Palatinae
830
LordHunter317":2ugcxhhd said:
No, you cannot assume that a TypeError raised by a function called by 'doSomething' ipso-facto means there is a bug in your application. Either you can handle a TypeError raised from doSomething or you can't. If you can, write a correct exception handler. If you can't, then you shouldn't write one at all.
If it's my convention that functions handle their own type/value checking, I can. So far I can only think of one case where I made a function delegate part of its type-checking to another function. As a second example,
Code:
try:
 r = UrbanDict["cromulent"]
except KeyError:
 r = "[Not Found]"
If I get into the except clause, I'd like to be certain that the KeyError was because the key didn't exist in that dict. For the built-in dict type, I assume as much, but if I'm querying some other kind of object that allows key indexing, it might very well be that a KeyError had been raised and not caught somewhere deep and unrelated to whether or not UrbanDict contained a value for "cromulent". If I accidentally catch that KeyError, I get erroneous behavior and I miss an opportunity to catch a bug. True, I can look up "cromulent" more than once in a LBYL approach which the Python tutorial says is unpythonic and warns about:
In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”.
or I can depend on the pythonic EAFP approach in which I make the assumption that a KeyError can only be raised in reference to the lookup I'm talking about in my try: block.

EmeraldArcana":2ugcxhhd said:
couldn't you handle this with a custom exception? Define a class
Code:
class DoSomethingException(Exception):
and raise it in your doSomething method.
Well, apart from the hassle of creating untold numbers of custom exceptions (at least one for each function?) this would still catch recursion or mutual recursion when I don't want to. Alternately I could create an exception type that takes a function as a parameter, and then raise MyException("Problem with...", this_func) but again, I still wouldn't be able to differentiate recursion.

koala":2ugcxhhd said:
Exceptions are for exceptional cases. Invalid user input is often dealt with exceptions in a lot of frameworks, but I don't think it's the right way to do it (unless there's another layer of validation in front of you and invalid input can only reach you in exceptional cases).
In my project, I differentiate between input from an input file, etc. vs. state that my program is supposed to be maintaining. For an input file, it goes through several layers of parsing and validation, and each layer has its own type of exception associated with invalid data, whereas data which is completely unexpected raises a TypeError. For example, if one layer is supposed to be changing little space-delimited tokens into objects, and it receives some invalid token, it raises the custom exception for that layer, but if it gets something that isn't even a non-empty string devoid of space, it'll raise a TypeError. The outer parsing layer then catches only the exception type of that inner layer and converts it into its own type of exception so that at the top level, I can get meaningful error messages that give the file, line#, and column# of the problem, even though the inner layers are not aware of the textual position of the data they're working on. (That's how it is for stage 3, anyway. There's still stages 1 and 2 that are just giant functions I wrote in one sitting when I was focused on the problem. They work, but I have no idea how. They return error-codes which are explained in the documentation. Not so convenient, as it requires looking up the documentation to find out what the problem was. These deserve a re-write at some point.)

... if someone else is going to touch your code...
They'd better not - I think it'd bring out the mama bear in me. Thankfully no one has a reason or desire to do so.

Alamout":2ugcxhhd said:
Twisting a new language to work the way you want to use it is Wrong™. You'll be much better off if you just learn how to use the language correctly.
I think of it as the poor-man's alternative to creating a language from scratch. Also, I wouldn't understand half as much about Python by now if I hadn't been messing with it to explore what I can do with it.

technophile":2ugcxhhd said:
I'm further confused. The OP said he was writing this Python code to prototype an app that will be built in another language anyway... so why all the scaffolding? You may as well either write it idiomatically, or just prototype it in Java or whatever anyway, rather than torturing the language into some sort of bastardized wanna-be-Java.
Yeah, the future of this project is still very unknown. And, no, I'd never really given Java any serious consideration. The faster language would probably be C, C++, or some home-rolled meta-programming language that writes compilable C code. I'm not sure I'd switch everything to a faster language - probably I'd write up some of the core to run as a server process of some sort that communicates with programs written in a more accessible batteries-included language like Python.

LordHunter317":2ugcxhhd said:
DavlinLotze":2ugcxhhd said:
I wrote a module that gives me the option of nesting classes to any depth without any extra indentation.
Bad idea, because nesting classes is a bad idea. I'm not sure why you have such a love affair with them, but a break-up would do you lots of good.
You may have a different way of arranging things, but for me it makes sense to group things together by topic, so I can refer to (using the example above) MyThing.Builder.Error instead of having to separately create MyThing, MyThingBuilder, MyThingBuilderError, etc. Then within a class I can refer to various related functions and values without hassles of remembering how I named these long things. If it's in the same class, it's just c.Whatever. If I took Binary Alchemy's suggestion of never using class methods and avoiding class constants, I'd have symbols proliferated all over that are all somehow related even though they don't "belong" to some common class. Like I said, that might work well for some people, but it's more disjointed than my mind can handle.

LordHunter317":2ugcxhhd said:
Anywhere in a class's methods, I can refer to the class with the identifier "c", or to the enclosing class, if there is one, with "outer".
I don't know how you can do this thread-safely without lots of extra work.
I'm not sure how thread-safety would play into it. In theory, this is all setup before any second thread would be started, since it's done while reading the module at the beginning.

LordHunter317":2ugcxhhd said:
(So I don't really have a use for the @classmethod decorator anymore, unless I'm missing something else it provides.)
What is the value of 'c' when calling a function defined on a parent class?
Whatever class the function belongs to is what 'c' refers to in that function. If I wanted the class of the instance, that's easy enough: self.__class__

The latest "gotcha" I ran across (learning the hard way helps you remember?) is never to use a mutable object as a function default unless you're really sure that's what you mean to do. If I'd thought about what I was doing, I knew better, but I wasn't thinking when I wrote something like:
Code:
def Foobar(spamdict={}):
 ...
Oddly enough, it worked fine on my limited testing, but when I woke up and realized that I hadn't finished implementing that part, I was a little baffled at why it "worked" until I saw how it "worked".
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":qupkrdm3 said:
If it's my convention that functions handle their own type/value checking, I can.
Nope, for a whole list of reasons:
  • Python library routines don't make that assumption and you will call them eventually.
  • I don't believe there's any 100% portable way to get the information you seek. You lock your code to the CPython interpreter.
  • That reasoning doesn't work with recursion. Recursion breaks you, though I admittedly don't know how a function would recurse into a TypeError.
  • There's a definite performance impact in redundant, unnecessary type checking.
  • It makes structuring your code sensibly impossible. Validation routines frequently call other routines in the process of performing validation. Your rule makes that impossible, negatively impacting your design.
  • Most importantly, as I said before, correct exception handling means you can handle any TypeError raised through doSomething(), regardless of where it happened in the call stack. If you cannot do that, then your exception handler itself is buggy or should not exist.
The last one is the most important. All you're doing here is attempting to eliminate one class of bug and creating a whole second class of bugs. Unfortunately, the second class is vastly more grave.

If I get into the except clause, I'd like to be certain that the KeyError was because the key didn't exist in that dict. For the built-in dict type, I assume as much, but if I'm querying some other kind of object that allows key indexing, it might very well be that a KeyError had been raised and not caught somewhere deep and unrelated to whether or not UrbanDict contained a value for "cromulent".
Perhaps, but irrelevant. If your code is written correctly you absolutely do not care. Even if it's a bug in the code you called.

Exception-safe code does not care where the exception originated. I cannot emphasize this enough. You're caring about something that is going to result in you writing bad, broken, buggy applications.

If I accidentally catch that KeyError, I get erroneous behavior and I miss an opportunity to catch a bug.
You get neither, if your code is truly exception-safe.



For an input file, it goes through several layers of parsing and validation, and each layer has its own type of exception associated with invalid data, whereas data which is completely unexpected raises a TypeError.
You're misusing the exception, which is part of the problem. TypeError is for invalid parameters, not really invalid input read from a file.

For example, if one layer is supposed to be changing little space-delimited tokens into objects, and it receives some invalid token, it raises the custom exception for that layer, but if it gets something that isn't even a non-empty string devoid of space, it'll raise a TypeError.
While it might be useful to distinguish different sorts of lexical errors, you should be writing your own exception hierarchy to do so.

The outer parsing layer then catches only the exception type of that inner layer and converts it into its own type of exception so that at the top level, I can get meaningful error messages that give the file, line#, and column# of the problem, even though the inner layers are not aware of the textual position of the data they're working on.
This is bad. Either just modify the exception in the top-level or pass the context downward. Do not wrap or replace the raised exception.

Also, I wouldn't understand half as much about Python by now if I hadn't been messing with it to explore what I can do with it.
You'd understand a whole lot more, and be writing much better code, if you'd just go read the reference manual. All of the problems you've described here are entirely of your own making, and the solution to all of them is "Stop doing that."

You may have a different way of arranging things, but for me it makes sense to group things together by topic, so I can refer to (using the example above) MyThing.Builder.Error instead of having to separately create MyThing, MyThingBuilder, MyThingBuilderError, etc.
I already showed you how you don't have to do that. Use modules, that's what they're there for! Literally, you have a language feature that does exactly what you want and you're not using it. That's bad.

Then within a class I can refer to various related functions and values without hassles of remembering how I named these long things.
There are tons of tools to help you with the cognitive load, but you still have to remember how you named them. Access to class attributes must always be qualified in some fashion. It's a language rule.

If I took Binary Alchemy's suggestion of never using class methods and avoiding class constants, I'd have symbols proliferated all over that are all somehow related even though they don't "belong" to some common class. Like I said, that might work well for some people, but it's more disjointed than my mind can handle.
It is no more disjointed than what you're doing, and we know this due to the language rules. There's not a subjective position here, if you understand how the language works.

I'm not sure how thread-safety would play into it. In theory, this is all setup before any second thread would be started, since it's done while reading the module at the beginning.
No. c must be module-scoped and is accessed at "runtime", so what happens if I call any of your "preprocessor" functionality at "runtime"?

Though the bigger concern is what happens if I attempt to define more than one class in a module? Which is the issue I meant to raise originally, but your explanation had me quite confused. Everything you're doing is very, very confusing.

LordHunter317":qupkrdm3 said:
(So I don't really have a use for the @classmethod decorator anymore, unless I'm missing something else it provides.)
What is the value of 'c' when calling a function defined on a parent class?
Whatever class the function belongs to is what 'c' refers to in that function. If I wanted the class of the instance, that's easy enough: self.__class__
See, that's not even remotely close to what @classmethod does. You should really go read the documentation.
 

ahankinson

Wise, Aged Ars Veteran
117
Yikes! If this code doesn't end up on the dailyWTF I will be very surprised. You're not writing Python, you're inventing your own language with Python.

Code:
from myhelpermodule import *     <-- importing into the global context is frowned upon, since you don't know if you're going to clobber something useful.
exec mhm_init                              <-- where is this defined? And why do you have to exec() it? 

Import("anothermodule", "eggs Cheese.Blue:BlueCheese toast")  <-- Are you defining your own Import() class to take the place of the standard import statement?

Class("MyThing")  <-- Uhhhh.... What's this?

Import("foo", "Bar", pinunder="c")   <-- Where is "c"? 

MyConstant = something()

def __init__(self):
 pass

Class("Builder")

Class("Error", "Exception", """This is the documentation for
the Error class.""")
EndClass()

@staticmethod
def DoSomething(spam):
 if spam is A_Problem:
  raise c.Error("Problem in '%s'." % this_func.__name__)

EndClass()  <-- If you have to do this, you shouldn't be writing Python. Either learn it, or write your application in another language. 

EndClass()

Cleanup()  <-- are you writing your own GC too??
 

DavlinLotze

Ars Scholae Palatinae
830
LordHunter317":3e9t2hk2 said:
See, that's not even remotely close to what @classmethod does. You should really go read the documentation.
Thanks, I didn't understand classmethod correctly. I still don't know what good they are, as I've never needed something like that.
I'm not sure how thread-safety would play into it. In theory, this is all setup before any second thread would be started, since it's done while reading the module at the beginning.
No. c must be module-scoped and is accessed at "runtime", so what happens if I call any of your "preprocessor" functionality at "runtime"?

Though the bigger concern is what happens if I attempt to define more than one class in a module? Which is the issue I meant to raise originally, but your explanation had me quite confused. Everything you're doing is very, very confusing.
If I'm understanding you correctly, "runtime", which you appropriately put in quotes, would be after the modules are loaded and you begin to do something more interesting, even though loading a module is technically running code. In that case, you wouldn't call any of my "preprocessor" functionality at "runtime", as that would be a misuse of it. 'c' is a global in the file while the file is being loaded, and it changes value as you go in and out of new classes, but it's also made a global within each method, so when you're calling the method later, 'c' has nothing to do with some global that may no longer exist.

Use modules, that's what they're there for!
Doesn't that mean that I'd be putting perhaps just a few lines of code in some files? While it's certainly possible to define multiple modules in a single file, it's not the regular way of things. And would you like me using modules nested in classes any better? Currently I use classes inheriting from a class I call "Static" as static classes. It is a bit of a hassle to mark each method with @staticmethod when that should be obvious - of course I could make that go away quite easily with my preprocessor, or perhaps better just automatically convert any "Static" classes into modules. But I don't think you'd like that any better. You've told me twice now, and Binary Alchemy too, to use modules, but you haven't said how to use modules - at least not in a way I understand that would give me the organizational flexibility I seek.

For an input file, it goes through several layers of parsing and validation, and each layer has its own type of exception associated with invalid data, whereas data which is completely unexpected raises a TypeError.
You're misusing the exception, which is part of the problem. TypeError is for invalid parameters, not really invalid input read from a file.

For example, if one layer is supposed to be changing little space-delimited tokens into objects, and it receives some invalid token, it raises the custom exception for that layer, but if it gets something that isn't even a non-empty string devoid of space, it'll raise a TypeError.
While it might be useful to distinguish different sorts of lexical errors, you should be writing your own exception hierarchy to do so.
I don't think you're understanding. The TypeError is only raised on input it should never have received. If a TypeError is raised, it indicates a problem with the outer parsing layer or previous stage of parsing and not simply an error in the file data being read.

The outer parsing layer then catches only the exception type of that inner layer and converts it into its own type of exception so that at the top level, I can get meaningful error messages that give the file, line#, and column# of the problem, even though the inner layers are not aware of the textual position of the data they're working on.
This is bad. Either just modify the exception in the top-level or pass the context downward. Do not wrap or replace the raised exception.
Can you explain your reasoning? My goal is to let each layer be oblivious to all layers except those which it directly calls. What does "pass the context downward" mean? If I attempt to "just modify the exception in the top-level", I will have missed out on prepending the context of the error message at each higher layer, so I might not understand what I was talking about. Leaving the outermost layer to catch all the exceptions doesn't let it remain oblivious of the implementation of the inner layers on which it depends or the types of exceptions they might raise. It should only have to know about the exceptions raised by the layer it directly accesses. Any other exceptions should float up and kill my program, albeit gracefully if need be. Are you saying that parsing exceptions from an inner layer should be created as subclasses of the outer layer's exception so that the outermost layer can just except: LayerOneError to catch them all? This still doesn't allow inner layers to be oblivious of the outer layers, since their errors have to be subclassed from the outer layer's errors (even though their structure and attributes should be completely different), and you still don't wrap the error messages in appropriate context. The inner layers don't know or care about files, lines, or columns. If there's not some converting of the exceptions along the way, there's no link established between them.

ahankinson":3e9t2hk2 said:
<-- importing into the global context is frowned upon, since you don't know if you're going to clobber something useful.
I don't get it. If this is a module I'm writing, I should know what's global. And given that this is the first statement in the file, how is there anything to clobber?
<-- where is this defined? And why do you have to exec() it?
Obviously it must be defined in myhelpermodule, as that's the only thing I've imported from, and it's not a built-in. It has to be exec'ed because it's a string. It sets up some functions and global variables that are used below.
<-- Are you defining your own Import() class to take the place of the standard import statement?
No, Import is a global function set up by exec'ing the init string, but yes, it does take the place of the standard import statement and adds a couple features.
Class("MyThing") <-- Uhhhh.... What's this?
It's like class MyThing(object): but designed to work with my "preprocessor" and doesn't make you indent everything below.
<-- Where is "c"?
'c' refers to the current class. It's updated any time "Class" or "EndClass" are run.
Cleanup() <-- are you writing your own GC too??
This just deletes the junk created by the "preprocessor" and makes sure that the classes and other things you defined are ready to be imported from another module.

LordHunter317":3e9t2hk2 said:
Most importantly, as I said before, correct exception handling means you can handle any TypeError raised through doSomething(), regardless of where it happened in the call stack. If you cannot do that, then your exception handler itself is buggy or should not exist.
I would like to understand you on this point, but so far I don't. In your view, then, what would be an acceptable use of try/except? How can an exception handler remain oblivious to the implementation of the things being 'try:'ed but still be sure to appropriately handle any exception of a particular type regardless of where they're raised in the call stack?

If I get into the except clause, I'd like to be certain that the KeyError was because the key didn't exist in that dict. For the built-in dict type, I assume as much, but if I'm querying some other kind of object that allows key indexing, it might very well be that a KeyError had been raised and not caught somewhere deep and unrelated to whether or not UrbanDict contained a value for "cromulent".
Perhaps, but irrelevant. If your code is written correctly you absolutely do not care. Even if it's a bug in the code you called.

Exception-safe code does not care where the exception originated. I cannot emphasize this enough. You're caring about something that is going to result in you writing bad, broken, buggy applications.

If I accidentally catch that KeyError, I get erroneous behavior and I miss an opportunity to catch a bug.
You get neither, if your code is truly exception-safe.
How can I not care when I clearly do? I can accept if you're telling me that exceptions shouldn't be used that way, but I don't see that you're telling me how they should be used or what alternative there is to using them in the way I mentioned. Do I just go back to a LBYL style (wrapped with locks, if needed)? Or do my exceptions just need to be more customized and explicit?: To take the example of KeyError, should KeyError really have two arguments - one for the key tried, and one for the object it was tried on, so that you can be certain to what the exception applied, e.g.:
Code:
wrd = "cromulent"
try:
 r = UrbanDict[wrd]
except MyKeyError as err:
 if err.Key() is wrd and err.Obj() is UrbanDict:
  r = "[Not Found]"
 else:
  raise
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
DavlinLotze":1wdmul94 said:
'c' is a global in the file while the file is being loaded, and it changes value as you go in and out of new classes, but it's also made a global within each method, so when you're calling the method later, 'c' has nothing to do with some global that may no longer exist.
I have no idea what you're actually doing, but that's not how the global statement works in Python. global merely changes where a name is searched for, it doesn't declare any new variables. There can only be one variable at module-scope named 'c'.

Doesn't that mean that I'd be putting perhaps just a few lines of code in some files?
Possibly, but I rather doubt it. You'd flatten things as I showed above.

While it's certainly possible to define multiple modules in a single file, it's not the regular way of things.
If you feel the need to do that, you're still organizing your code incorrectly.

And would you like me using modules nested in classes any better?
That's impossible.

Currently I use classes inheriting from a class I call "Static" as static classes.
There really is no such thing in Python. Moreover, valid uses of static methods is very rare.

You've told me twice now, and Binary Alchemy too, to use modules, but you haven't said how to use modules - at least not in a way I understand that would give me the organizational flexibility I seek.
That's because we have no idea what organizational flexibility you seek, nor what you're trying to accomplish that modules cannot do. What is apparent is that you don't understand them, but I'm not prepared to tell you to do much else but read the documentation at this point.

I don't think you're understanding. The TypeError is only raised on input it should never have received. If a TypeError is raised, it indicates a problem with the outer parsing layer or previous stage of parsing and not simply an error in the file data being read.
Ok fine, but you're still probably misusing it. TypeError is only for when the wrong type is passed, or when an illegal operation is performed upon a type. Invalid values result in a ValueError. Regardless, it may still be prudent to define your own exceptions.

Can you explain your reasoning? My goal is to let each layer be oblivious to all layers except those which it directly calls.
Because exception chaining is a relatively new Python feature and you risk destroying useful information; alternatively, you have to do a lot of work to compensate for the lack of chained exceptions. At any rate, your goal is not really possible, so it's not something to attempt to achieve. For the same sort of reasons I've already explained.

Another reason: Even if your outer layer knows all the exceptions thrown by the inner layer, it cannot know all the exceptions thrown by the objects passed to the inner layer. In general, it is impossible to write any Python function that take arguments and has a known set of potential exceptions. I can always create a custom type that throws an exception you handle but did not anticipate being thrown in that context.

What does "pass the context downward" mean?
Pass the filename and line down to where the exception gets generated.

If I attempt to "just modify the exception in the top-level", I will have missed out on prepending the context of the error message at each higher layer, so I might not understand what I was talking about.
How? You catch and re-raise as necessary, each time you want to modify the exception. But doing that is probably not necessary anyway, since you have a stack trace. Adding information for people outside your library is fine, but you should probably only need to do that in one place.

Leaving the outermost layer to catch all the exceptions doesn't let it remain oblivious of the implementation of the inner layers on which it depends or the types of exceptions they might raise. It should only have to know about the exceptions raised by the layer it directly accesses.
That's just not possible. It's not possible to hide these things without a ton of replication of the exception hierarchy, which inherently gives away what happened in the lower layers. How are you going to cover up an IOError, for example? More importantly, as I said above, you must write your code based on the general notion that any exception could happen at anytime.

Are you saying that parsing exceptions from an inner layer should be created as subclasses of the outer layer's exception so that the outermost layer can just except: LayerOneError to catch them all?
No, I'm saying you should do this:
Code:
class ValidationException(Exception):
    pass

def validate(input):
     if input != "Good":
          raise ValidationException()

def parse(file):
     for i, line in enumerate(file):
         try:
              validate(line)
         except ValidationException as e:
              e.line = i
              e.name = file.name
              raise
There's no need to make it more complicated. If you have several different types, then it might be reasonable to inherit from a common exception type. But you certainly don't have to do that.

I don't get it. If this is a module I'm writing, I should know what's global.
Yeah, but that's a terrible habit and practice to get into. Not all modules are 'from X import *' safe, so the convention is to generally never do it.

I would like to understand you on this point, but so far I don't. In your view, then, what would be an acceptable use of try/except? How can an exception handler remain oblivious to the implementation of the things being 'try:'ed but still be sure to appropriately handle any exception of a particular type regardless of where they're raised in the call stack?
Given the above, like so:
Code:
import sys

if __name__ == '__main__':
    for name in sys.argv:
        try:
            parse(open(name, 'r'))  # Ignore the terrible resource management. 
        except IOError, e:
            print >> sys.stderr, '{0}: {1}'.format(name, e)
        except ValidationError, e:
            print >> sys.stderr, '{0}:{1}: ValidationError'.format(e.name, e.line)
Not that it doesn't matter if parse() raises ValidationError, or calls validate(), or if validate() isn't called until 10 calls down the stack. My exception handler will do the right thing. Note that you could also move opening the file inside parse(), and still it would do the right thing. The other, equally important part, is to never write an exception handler for an exception you cannot handle, and never write an exception handler that doesn't actually respond to the exception in some useful manner.

I can accept if you're telling me that exceptions shouldn't be used that way, but I don't see that you're telling me how they should be used or what alternative there is to using them in the way I mentioned.
You use exceptions to abandon the normal flow of control and unwind the stack until the situation can be handled, if it can be handled at all. You write an exception handler to respond to the condition. Part of doing that correctly means not caring about how far the stack was unwound. The entire point is to support unwinding the stack an arbitrary depth.

Do I just go back to a LBYL style (wrapped with locks, if needed)? Or do my exceptions just need to be more customized and explicit?:
Neither, you need to just stop vastly overthinking the problem. If you write:
Code:
try:
    x = Options['foo']
except KeyError:
    x = DEFAULT_FOR_FOO
You don't care whether KeyError was raised in Options.__getitem__ or something function called by Options.__getitem___. The response is the same no matter where the KeyError was raised. You have yet to show why the response should be different, or even how you could do anything else. So what if the KeyError being returned was actually a bug? Knowing how far down the stack it occurred doesn't help you detect bugs, because Options.__getitem__ itself could be:
Code:
class Options(object):
     def __getitem__(self, key):  # Too lazy, make them always use a default
          raise KeyError('No Item For You')
Which is obviously legal, but perhaps not what was intended.
 

DavlinLotze

Ars Scholae Palatinae
830
LordHunter317":1he66wza said:
DavlinLotze":1he66wza said:
And would you like me using modules nested in classes any better?
That's impossible.
How is that impossible? Existing module or new, it's easy:
Code:
>>> class B: pass
... 
>>> B.sys = __import__("sys")
>>> B.sys
<module 'sys' (built-in)>
>>> import types
>>> B.Frank = types.ModuleType("Frank")
With my preprocessor, I could make it even more streamlined.

LordHunter317":1he66wza said:
DavlinLotze":1he66wza said:
Currently I use classes inheriting from a class I call "Static" as static classes.
There really is no such thing in Python.
I know. Static is just a class I inherit from as a personal convention. All it contains is an __init__ that calls you names if you try to instantiate from any such class. Nested modules, as "impossible" as they are would be a perfect replacement for them and save me typing @staticmethod, and wouldn't change the naming scheme at all.

Ok fine, but you're still probably misusing it. TypeError is only for when the wrong type is passed, or when an illegal operation is performed upon a type. Invalid values result in a ValueError. Regardless, it may still be prudent to define your own exceptions.
I know "type" has a specific meaning in python, but given that it's a dynamically typed language where identifiers don't even have a particular type to which they must conform, and mixing around various "compatible" types is rather encouraged, the idea of type gets a little mushy, so I've just been using TypeError for any bad data the function isn't otherwise qualified to deal with. I thought about making an UndefinedInputError or something like that, but I haven't really had a huge reason to yet. I just use TypeError to trigger my program to die. I usually don't even bother with a message unless I think I need to remind myself when looking at that bit of code what condition I was testing for.

My goal is to let each layer be oblivious to all layers except those which it directly calls.
... At any rate, your goal is not really possible, so it's not something to attempt to achieve.
How is that impossible? Each layer has a contract, if you will, about what it does: "You give me x, I'll return y. You give me z, I'll raise you an Error(z)." The outer layers do NOT need to know or care if the layer they access does all the work, or only some of it and passes the rest on to various other layers. Likewise, the inner layers don't need to know anything about how they're used - they just need to do what they're supposed to do.

What does "pass the context downward" mean?
Pass the filename and line down to where the exception gets generated.
Ok, but the inner layers don't need to have anything to do with details of the outer layers - it just complicates them and doesn't properly separate concerns; it isn't as modular.

If I attempt to "just modify the exception in the top-level", I will have missed out on prepending the context of the error message at each higher layer, so I might not understand what I was talking about.
How? You catch and re-raise as necessary, each time you want to modify the exception. But doing that is probably not necessary anyway, since you have a stack trace. Adding information for people outside your library is fine, but you should probably only need to do that in one place.
I see; so you think modifying the exception as it's passed up is okay, but not replacing it completely? I'm not interested in keeping any kind of stack trace - I just want to know the nature of the problem and where the problem is. In a GUI context, I'd be loading a file, then, if there's a problem, looking at a simple error message - possibly with more advanced functionality, it'll point right at the problem in its context, either by showing content from the file, or more easily by launching an editor to load that file and go to ln#, col#. I have no interest in looking at stack traces unless there's a problem with the program itself.

Even if your outer layer knows all the exceptions thrown by the inner layer, it cannot know all the exceptions thrown by the objects passed to the inner layer. In general, it is impossible to write any Python function that take arguments and has a known set of potential exceptions. I can always create a custom type that throws an exception you handle but did not anticipate being thrown in that context.
That's why I use custom error types - one per layer in this case - so that if I'm only handling the exceptions raised by that inner layer, I'm reasonably certain they weren't raised by some inner layer or function called by an inner layer, but only by the layer directly accessed. If there's any other sort of trouble, I want that trouble to surface and kill my program without mercy so I can look at the stack trace and fix the bug.

Leaving the outermost layer to catch all the exceptions doesn't let it remain oblivious of the implementation of the inner layers on which it depends or the types of exceptions they might raise. It should only have to know about the exceptions raised by the layer it directly accesses.
That's just not possible. It's not possible to hide these things without a ton of replication of the exception hierarchy, which inherently gives away what happened in the lower layers. How are you going to cover up an IOError, for example? More importantly, as I said above, you must write your code based on the general notion that any exception could happen at any time.
I don't understand your second sentence. I have no reason to cover up an IOError from the inner layers, as none of them deal with I/O. As for the one stage that does read from a file, it depends on the nature of the IOError as to how it would handle it. I haven't really fleshed out that part of the program yet. I understand the gist of your last sentence, but it's overstated. Not any exception can happen at any time. There are specific exceptions I'm going to try to handle (those specific to the systems this section of code uses), whereas other exceptions should make my program die. Since it seems that custom exceptions are the only feasible way to be reasonably certain where a particular exception came from, that's what I have to make. If that's "a ton of replication of the exception hierarchy", then so be it - I'd rather do that than handle exceptions I wasn't supposed to catch.

Code:
class ValidationException(Exception):
    pass

def validate(input):
     if input != "Good":
          raise ValidationException()

def parse(file):
     for i, line in enumerate(file):
         try:
              validate(line)
         except ValidationException as e:
              e.line = i
              e.name = file.name
              raise
I can't say I'm comfortable adding ad-hoc attributes to an instance in one function to be consumed by who-knows-what somewhere else.

Not all modules are 'from X import *' safe, so the convention is to generally never do it.
So I've read. (Yes, I do have, read, and refer back to the documentation as much I feel I need to. It's often not helpful in what I'm looking for, so I have to look online. Occasionally it's just plain wrong. Sometimes I run into undocumented "features" that the BDFL explains in forum posts will not be fixed because not enough people complained.) My preprocessor is the only module I currently use wildcard imports with. I wrote it, so I know exactly what it does. I could spell out the two identifiers it contains, but it's not worth the hassle.

you need to just stop vastly overthinking the problem. ... So what if the KeyError being returned was actually a bug?
Uh... You might not care, but I do.
Code:
defaultdict = {"AAA":"roadside assistance", "aardvark":"a mammal"}
class MultiDict:
 def __init__(self, *dicts): # dicts contains 2-tuples: (Name str, Dict dict)
  self.dicts = {}
  for d in dicts:
   self.dicts[d[0]] = d[1]
  self.dicts["Default"] = defaultdict
 def __getitem__(self, key):
  currentdict = self.dicts["default"] #search default first
  try: return currentdict[key]
  except KeyError:
   for currentdict in self.dicts.itervalues():
    try: return currentdict[key]
    except KeyError: continue
  raise KeyError(key)

oed = {} ; ahd = {}
grandUnifiedDict = MultiDict(("American Heritage Dictionary", ahd), ("Oxford English Dictionary", oed))

try:
 print grandUnifiedDict["AAA"]
except KeyError:
 print "Not found"
To be sure, the above example is a little convoluted and silly, but most bugs are silly in some way. In this example, "Not found" is printed, not because "AAA" isn't in one of the dictionaries, but because I had a bug in __getitem__ where I spelled "default" uncapitalized. If instead, as in my earlier "MyKeyError" example, the KeyError being handled could definitely be linked to the lookup of "AAA" in grandUnifiedDict, there would be no question. As it is, the behavior is erroneous and doesn't reveal the bug except through that erroneous behavior.

LordHunter317":1he66wza said:
DavlinLotze":1he66wza said:
'c' is a global in the file while the file is being loaded, and it changes value as you go in and out of new classes, but it's also made a global within each method, so when you're calling the method later, 'c' has nothing to do with some global that may no longer exist.
I have no idea what you're actually doing, but that's not how the global statement works in Python. global merely changes where a name is searched for, it doesn't declare any new variables. There can only be one variable at module-scope named 'c'.
I know. Sorry for trying to spare you the boring details about an idea you have no use for. Let me see if I can make this plain: 'c' has a particular value within the module while the module is being loaded/run. It changes value depending on what class I'm "in". (I know I'm never "in" a class by python standards - instead the preprocessor just makes an empty class and you start adding things to it until you "EndClass()". By "in a class", I simply mean between a call to "Class()" and its corresponding "EndClass()".) At the end of the file, when I run "Cleanup()", it deletes 'c', 'Class', 'EndClass', and all that other junk so they can't/won't be imported by another file. But my preprocessor also makes 'c' available to each method in a class. It does this by taking the code and other properties of the function and combining it with a new "func_globals" dict that contains the appropriate values for 'c', 'this_func', etc. It is this modified function which is tacked onto 'c' (whatever 'c' happens to currently be) under the same name with which it was defined.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I'm not interested in keeping any kind of stack trace

:eyebrow: Ah, I see you just want to make life difficult. Might I suggest starting with Brainfuck, move onto Befunge and see if you can get to INTERCAL.

In all seriousness why on earth aren't you simply getting yourself a DSL appropriate to what you want to do rather than bastardize python into something utterly bemusing to anyone using it.

I mean if you want to do a fast prototype deciding to rewrite the language from within in a language explicitly not designed for this is just not helpful. Using a Lisp, Nemerle, perhaps Scala or Dylan would make more sense. Alternatively many functional programming languages' pattern matching and discriminated unions constructs permit power, but slightly more limited embedded DSL's very well.

If you pick the wrong tool for the job, if the right tool exists, you have only yourself to blame, not the tool.

Taking python and attempting to eliminate some indentation requirements is just mind boggling.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
I have no clue what you're trying to accomplish but it's quite apparent, assuming you're even actually serious, that you need a lot of help, and that it's not possible to deliver such help over this medium. I'd advice you to read all of the Python reference documentation very closely. Otherwise, I don't think I can help you, as you're simply not listening to me.

DavlinLotze":2rqr9nqp said:
How is that impossible? Existing module or new, it's easy
That's not nesting a module, it's importing a module and retaining a reference (pointer) to it. Nesting means you've actually defined the module body inside the class, which cannot be done. The best you can do is define the module at runtime, but even then, I can access it through other mechanisms.

I know "type" has a specific meaning in python, but given that it's a dynamically typed language where identifiers don't even have a particular type to which they must conform, and mixing around various "compatible" types is rather encouraged, the idea of type gets a little mushy,
No, it doesn't. Type has a well-defined, well-understood meaning in Python. The fact that variables themselves are untyped doesn't change that. The fact that duck typing is supported doesn't change that either. Accordingly, TypeError has a well-defined, well-understood usage and you are misusing it.

How is that impossible? Each layer has a contract, if you will, about what it does: "You give me x, I'll return y. You give me z, I'll raise you an Error(z)."
Because I can write an x that raises Error(z) whenever you call any of its methods. As I said earlier, it's essentially impossible to make any formal guarantees about what exceptions will be thrown by a function that takes arguments. Therefore, correct code is written to the assumption that any exception can be thrown anywhere at anytime.

I see; so you think modifying the exception as it's passed up is okay, but not replacing it completely? I'm not interested in keeping any kind of stack trace - I just want to know the nature of the problem and where the problem is.
That's precisely what a stack trace is for!

Your incredible and absurd desire to replace every last useful language facility with your own bastardized version is why everyone thinks you're trolling.

In a GUI context, I'd be loading a file, then, if there's a problem, looking at a simple error message - possibly with more advanced functionality, it'll point right at the problem in its context, either by showing content from the file, or more easily by launching an editor to load that file and go to ln#, col#.
So do that. You don't have to show the stack trace in the GUI. But the GUI also doesn't need all this additional context you're talking about either!

That's why I use custom error types - one per layer in this case - so that if I'm only handling the exceptions raised by that inner layer, I'm reasonably certain they weren't raised by some inner layer or function called by an inner layer, but only by the layer directly accessed. If there's any other sort of trouble, I want that trouble to surface and kill my program without mercy so I can look at the stack trace and fix the bug.
(emphasis mine) No, you're missing the point. You cannot make that assumption ever, because I can always pass you an object that violates that assumption. Correct code is written to the notion any exception can be thrown at anytime, anywhere.

I don't understand your second sentence. I have no reason to cover up an IOError from the inner layers, as none of them deal with I/O.
So pick any other common and low-level exception then that must be filtered up to the top. You'll end up creating an exception at every layer[1] with almost the same name; you cannot hide what's going on.

I understand the gist of your last sentence, but it's overstated. Not any exception can happen at any time. There are specific exceptions I'm going to try to handle (those specific to the systems this section of code uses), whereas other exceptions should make my program die. Since it seems that custom exceptions are the only feasible way to be reasonably certain where a particular exception came from, that's what I have to make.
Nope, because I can write an object that raises your custom exception when you use it. You can't stop me from doing that, and it's pointless to even try. Your entire quest here is foolish, impossible, and will lead to bugs.


I can't say I'm comfortable adding ad-hoc attributes to an instance in one function to be consumed by who-knows-what somewhere else.
Why not? It's how Python works. If you're that uncomfortable with it, then you shouldn't be using the language at all.

(Yes, I do have, read, and refer back to the documentation as much I feel I need to. It's often not helpful in what I'm looking for, so I have to look online. Occasionally it's just plain wrong. Sometimes I run into undocumented "features" that the BDFL explains in forum posts will not be fixed because not enough people complained.)
While the CPython language reference has its problems, I seriously doubt you've legitimately run into any of them.

Uh... You might not care, but I do.
You don't, and you can't, because as I already demonstrated, exceptions are not a bug detection mechanism! Stop trying to use them as such. Any attempt to do so will just introduce bugs.


To be sure, the above example is a little convoluted and silly,
It's just awful, is what it is. I'm not sure what you think that code does, but it either doesn't do what you think it does, or it's entirely unnecessary.

If instead, as in my earlier "MyKeyError" example, the KeyError being handled could definitely be linked to the lookup of "AAA" in grandUnifiedDict, there would be no question.
It is definitely linked to that operation, but that doesn't let you determine whether the exception was caused by a bug or not! You clearly don't understand what your own code is doing!

It does this by taking the code and other properties of the function and combining it with a new "func_globals" dict that contains the appropriate values for 'c', 'this_func', etc. It is this modified function which is tacked onto 'c' (whatever 'c' happens to currently be) under the same name with which it was defined.
Such an operation is not supported and I'm somewhat amazed it even worked. What you're doing is bad and unsupported. While it seems to work on CPython (at least right now), it will not work in the future and on most other interpreters.

[1] Though the fact your serialization software has "layers" is absolutely fucking terrifying, to be honest with you. Either this is the file format from hell or you're grossly over-complicating ever last little damn thing. It also means you probably shouldn't be coding anything at all yet, because you still don't understand what you need to accomplish.
 

herko

Tone down Your Control issues.
7,012
Moderator
This is the most horrifying misuse/abuse of Python I've ever seen. And I've coded some doozies in the past.

I strongly suggest you pick up MUMPS (also called M), as it seems to be full of the features you want. You can even rename keywords to your heart's content, because everything's context-dependant.

How is that impossible? Existing module or new, it's easy:
Code:
>>> class B: pass
...
>>> B.sys = __import__("sys")
>>> B.sys
<module 'sys' (built-in)>
>>> import types
>>> B.Frank = types.ModuleType("Frank")
With my preprocessor, I could make it even more streamlined.

Why would you ever want to do that? You're structuring your code in ways that are profoundly alien to anyone who's ever read a well-written Python program. Just because you can do it doesn't mean that you should do it.

I just use TypeError to trigger my program to die. I usually don't even bother with a message unless I think I need to remind myself when looking at that bit of code what condition I was testing for.
Aside from the TypeError misuse, this is also strange for someone who claims to want to know the exact place where programs die. Anyway, you don't want to bother with stack traces, but you don't have to; python will do it for you. The traceback module will give you nicely formatted output detailing the exception, line number, and file where an error occurred. Like magic. By default it'll format the messages like python does, but you can easily use its contents and do whatever you want with them.

Code:
>>> import traceback, sys
>>> def bad_function():
...     a=1
...     b=0
...     return a/b
... 

>>> bad_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in bad_function
ZeroDivisionError: integer division or modulo by zero

>>> # So far so good; let's show that an exception handler can extract the same message.
>>> try:
...     bad_function()
... except ZeroDivisionError:
...     print "Hey, dude, your function sucks. Here's the skinny:"
...     print traceback.format_exc()
...     print "And that is all I have to say on the subject."
... 
Hey, dude, your function sucks. Here's the skinny:
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 4, in bad_function
ZeroDivisionError: integer division or modulo by zero

And that is all I have to say on the subject.

>>> # Let's play with the contents of the stack trace
>>> try:
...     bad_function()
... except ZeroDivisionError:
...     exception_info=sys.exc_info()
...     exception_type, extra_info, stack_trace=exception_info
...     print "An exception of type", exception_type, "completely bummed me out."
...     print "It said '", extra_info , "'"
...     print "Here is what was going on at the moment."
...     for entry in traceback.extract_tb(stack_trace):
...         filename, linenumber, function, message=entry
...         print "This is my own traceback format. Line", linenumber, "in file '", filename, "' died horribly when in function '", function, "' with this message:", message
An exception of type <type 'exceptions.ZeroDivisionError'> completely bummed me out.
It said ' integer division or modulo by zero '
Here is what was going on at the moment.
This is my own traceback format. Line 2 in file ' <stdin> ' died horribly when in function ' <module> ' with this message: None
This is my own traceback format. Line 4 in file ' <stdin> ' died horribly when in function ' bad_function ' with this message: None

>>> # In fact, that is the same information that the system-wide exception hook gets, so you can replace the system-wide exception hook with something similar
>>> def my_little_pony_exception_hook(exception_type, extra_info, stack_trace):
...     print "An exception of type", exception_type, "was not friendly nor magical."
...     print "It whinnied '", extra_info , "'"
...     print "Here is what was going on in Celestia at the moment."
...     for entry in traceback.extract_tb(stack_trace):
...         filename, linenumber, function, message=entry
...         print "Line", linenumber, "in file '", filename, "' died horribly when in function '", function, "' with this message:", message 
... 

>>> sys.excepthook=my_little_pony_exception_hook # <-- replace the system-wide exception hook

>>> 1/0
An exception of type <type 'exceptions.ZeroDivisionError'> was not friendly nor magical.
It whinnied ' integer division or modulo by zero '
Here is what was going on in Celestia at the moment.
Line 1 in file ' <stdin> ' died horribly when in function ' <module> ' with this message: None

>>> bad_function()
An exception of type <type 'exceptions.ZeroDivisionError'> was not friendly nor magical.
It whinnied ' integer division or modulo by zero '
Here is what was going on in Celestia at the moment.
Line 1 in file ' <stdin> ' died horribly when in function ' <module> ' with this message: None
Line 4 in file ' <stdin> ' died horribly when in function ' bad_function ' with this message: None

>>> {}['unknown_key']
An exception of type <type 'exceptions.KeyError'> was not friendly nor magical.
It whinnied ' 'unknown_key' '
Here is what was going on in Celestia at the moment.
Line 1 in file ' <stdin> ' died horribly when in function ' <module> ' with this message: None

>>> # I pressed control-c here
An exception of type <type 'exceptions.KeyboardInterrupt'> was not friendly nor magical.
It whinnied '  '
Here is what was going on in Celestia at the moment.
>>>

You get the idea.
 

DavlinLotze

Ars Scholae Palatinae
830
herko":1sa1i37w said:
I strongly suggest you pick up MUMPS (also called M), as it seems to be full of the features you want. You can even rename keywords to your heart's content, because everything's context-dependant.
Yipes. Unlike ShuggyCoUk's 3 initial suggestions, it looks like people actually use that language for "real" programs. No, thanks - Python is plenty flexible in that regard:
Code:
>>> a = True ; True = False ; False = a ; print True,False
False True

But thank you, Brony herko, for enlightening me with your IDLE-foo - it really is magic - I've never seen that before! Who knew you could actually see a stack trace get printed? [/sarcasm]

It seems you and LH317 and Shuggy (though his was possibly just in jest) have taken what I said about not caring about stack traces completely out of the context of what I said. Likewise, you've misunderstood (or misrepresented) when I said:
I'm not interested in keeping any kind of stack trace - I just want to know the nature of the problem and where the problem is.
Obviously, the "where" there has to do with where in the textual input (file name, line, column) is the parsing error, unrecognized token, etc. Obviously if it were a problem with my program, I'd want to see a stack trace. But a problem with the input is completely different. Since the parsing layers have their own associated exception types, the outer-layer consumers of this functionality don't need to know, and shouldn't even try to mess with stack trace junk. The only person for whom a stack trace is helpful is a programmer trying to fix the error that caused him to be looking at a stack trace.

ShuggyCoUk":1sa1i37w said:
why on earth aren't you simply getting yourself a DSL appropriate to what you want to do
Tools related to my own DSL are exactly what I'm making. The choice to use Python was really somewhat of a toss-up - I just had to pick something. I've liked and disliked things about every programming language I've ever used. I don't get along very well with living in somebody else's house, so to speak. If I'm going to use a language, I'm going to mess around with it, find out its perks and quirks, and move in - make it my own. I never program with other people, so I don't give a darn about language conventions, stylistic conventions, or programming idiomatically. If I knew every computer language ever made, it's possible I might have chosen something other than Python, but I've used enough programming languages to get a good feel for what's out there. I'm not really concerned if you cringe at the way I (ab)use python. You should see how I've (ab)used other languages. Python's dynamic nature at least makes some types of changes easier, even if it has a rather pathetic set of control structures (no do-while, goto, gosub/return, select case, etc. - I list only ones that exist in other languages - not all the ones that exist in my mind that I've never seen in a programming language.)

ShuggyCoUk":1sa1i37w said:
Taking python and attempting to eliminate some indentation requirements is just mind boggling.
Stuff like eliminating indentation and allowing "this_func" were just perks - that wasn't my original goal - just gems I picked up along the way.

LordHunter317":1sa1i37w said:
That's not nesting a module, it's importing a module and retaining a reference (pointer) to it. Nesting means you've actually defined the module body inside the class, which cannot be done.
It comes down to the same thing. If you want to play that semantics game, then you needn't tell me that nesting classes is a bad - I don't nest classes anymore - I merely "retain a reference to" one class as a class attribute of another class.

TypeError has a well-defined, well-understood usage and you are misusing it.
Okay; I don't mind. Like I said, it's immaterial to me whether I use TypeError, ValueError, or something home-grown like UndefinedInputError. If I'm checking the validity of an argument, I may just ship it off to some predicate to get a True or False. If it fails the test, I don't really care how it failed - I just know it failed. I'm not going to sit there and pick apart the bad input to decide whether to raise a TypeError or a ValueError. It's just a "it failed; die now; see stack trace; fix bug" moment.

On the other hand, if user input fails at some level of parsing, that's quite different - I'm going to raise an exception associated with that level and include an explicit message about how/why it was invalid.

How is that impossible? Each layer has a contract, if you will, about what it does: "You give me x, I'll return y. You give me z, I'll raise you an Error(z)."
Because I can write an x that raises Error(z) whenever you call any of its methods. As I said earlier, it's essentially impossible to make any formal guarantees about what exceptions will be thrown by a function that takes arguments. Therefore, correct code is written to the assumption that any exception can be thrown anywhere at anytime.

Python is all but devoid of formal guarantees in general. You can mess around with what should be protected attributes (like __slots__), add ad hoc attributes, add stuff or delete stuff from __builtins__, change the value of True, False, Ellipsis, etc. For old-style classes you can even change the __class__ of an instance. I don't think this is about "formal guarantees". Sure, you can raise random exceptions without a good reason, but first of all, why would I call methods on your sabotaged 'z' until I'd at least checked its type and had a reasonable idea of what it is?

Code:
class FooError: pass
def Foo(spam):
 try: spamiter = iter(spam)
 except TypeError: raise TypeError("Iterable type required.")
 try: first = spamiter.next()
 except StopIteration: raise TypeError("Non-empty iterable required.")
 if type(first) is not int: raise TypeError("Must only contain ints.")
 if first == 3: raise FooError
The question is not whether or not a FooError could be raised when I attempt to iterate your spam, but would it be reasonable, given a situation in which iteration of 'spam' has nothing to do with 'Foo'ing. In other words, if it would require deliberate sabotage to make spam iteration raise a FooError, then you deserve the mess you get. If on the other hand the situation is that spam iteration may very well raise a FooError because Fooing is a common thing to do, then I'd want to make the exceptions more explicit, like so:
Code:
class FooError:
 def __init(self, message, obj, badval, index):
  if type(index) is not int: raise TypeError
  elif type(msg) is not str: raise TypeError
  elif type(badval) is not int: raise TypeError
  try: obj.__iter__
  except AttributeError: raise TypeError
  self.message = message
  self.obj = obj
  self.badval = badval
  self.index = index
  
def Foo(spam):
 try: spamiter = iter(spam)
 except TypeError: raise TypeError("Iterable type required.")
 try: first = spamiter.next()
 except StopIteration: raise TypeError("Non-empty iterable required.")
 if type(first) is not int: raise TypeError("Must only contain ints.")
 if first == 3: raise FooError("First number can't be prime", spam, first, 0)
In this case, I'd know when I handled the FooError that the FooError applied to my 'spam', and wasn't just another unhandled FooError raised in the process of servicing my Foo(spam) request.

Knowing whether the first is required, or the second, depends on the situation. As it is, I'm a little screwed in either case by having to except the generic StopIteration which has no arguments with which I can discriminate a StopIteration that was raised by there being nothing in 'spam' from some unrelated StopIteration that was raised and not handled in the process of iterating 'spam'.

While the CPython language reference has its problems, I seriously doubt you've legitimately run into any of them.
Yeah, I have, and I've taken the time to email some to docs@python.org. Still waiting to see if they fix them. Your doubt doesn't even make sense: If you admit it has its problems, why would it seem unlikely that I've run into any? Oh, yeah, that's right - you think all my "troubles" stem from not reading the documentation, so how could I possibly have come across errors in the documentation? But at the risk of acting like I have something to prove, here's one of them:
If an attempt is made to release an unlocked lock, a RuntimeError will be raised.
...
Lock.release()
...
When invoked on an unlocked lock, a ThreadError is raised.
ThreadError is not RuntimeError, nor does it inherit from it. They really confused themselves by the implementation, not just the documentation:
Code:
>>> from threading import RLock
>>> mylock = RLock()
>>> mylock.release()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/threading.py", line 142, in release
    raise RuntimeError("cannot release un-acquired lock")
RuntimeError: cannot release un-acquired lock
>>> from threading import Lock
>>> yourlock = Lock()
>>> yourlock.release()  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
thread.error: release unlocked lock
>>>


If instead, as in my earlier "MyKeyError" example, the KeyError being handled could definitely be linked to the lookup of "AAA" in grandUnifiedDict, there would be no question.
It is definitely linked to that operation, but that doesn't let you determine whether the exception was caused by a bug or not!
If by "determine" you're talking about formal guarantees again, no. There's nothing keeping you from being an asshole and raising a MyKeyError() that "just happens" to point to the wrong key and dictionary in its args, and these incorrect args "just happen" to be the very dictionary and key being searched earlier in the call stack, but that's not the sort of thing bugs are made of - that's the sort of thing deliberate sabotage is made of.


Such an operation is not supported and I'm somewhat amazed it even worked. What you're doing is bad and unsupported. While it seems to work on CPython (at least right now), it will not work in the future and on most other interpreters.
I see; so they were just wasting their time making functions first class objects and creating a whole interface for their various attributes, like __globals__, and then documenting it in the reference manual because they really didn't intend anyone to actually use these features. I'm well aware that what I do now may possibly not work in future versions. But that's the way it is with lots of things. The word "currently" gets quite a workout in the Python manuals. While the trend is to start locking down certain things for performance reasons, access to function attributes actually looks like it's something they intend to expand:
Changed in version 2.4:
func_name is now writable. Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and
set such attributes. Note that the current implementation only supports function attributes on user-defined
functions. Function attributes on built-in functions may be supported in the future.

Though the fact your serialization software has "layers" is absolutely fucking terrifying, to be honest with you. Either this is the file format from hell or you're grossly over-complicating ever last little damn thing. It also means you probably shouldn't be coding anything at all yet, because you still don't understand what you need to accomplish.
Oh, I'm sorry - is "modularity" a bad word around here? I guess I should have just written the whole parsing process in one ginormous function and then rewritten half of it when I needed only certain parts of that functionality.

But you're almost right about one aspect - that I don't know exactly how to do everything that must be done, or even know what all must be done. To be sure, there was plenty of work done "on paper" and in the mind before coding began, but there are some things that it's hard to anticipate exactly how they'll work together until you have a working prototype. This is actually the 8 or 9th generation of this program's prototype - most of them abandoned quite early in the game. The actual project has been around longer than that. This version is a complete rewrite in a different language with all different specs that are continually changing. One more reason why I want modularity. It means I can add/remove functionality by just messing with a few things. I can even support completely different specs simultaneously because the text representation isn't inseparably wed to the objects which they represent.
 

Alamout

Ars Legatus Legionis
27,285
Oh, I'm sorry - is "modularity" a bad word around here?
Normally no, but you manage to make it sound like an obscenity.

A lot of programmers--who are much, much more experienced than you--are telling you that you are making a big mistake. You should listen to them instead of getting angry at them. They are right, and you are wrong, and if you don't understand why they are right then you need to study their arguments until you do.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Tools related to my own DSL are exactly what I'm making. The choice to use Python was really somewhat of a toss-up - I just had to pick something. I've liked and disliked things about every programming language I've ever used. I don't get along very well with living in somebody else's house, so to speak. If I'm going to use a language, I'm going to mess around with it, find out its perks and quirks, and move in - make it my own. I never program with other people, so I don't give a darn about language conventions, stylistic conventions, or programming idiomatically.

Then, regardless of your opinion on anything else in the thread, you must surely agree that your Title is grossly misleading.

What you are doing is *guaranteed* to cause more headaches, and you have no intention of changing much of it.

There's simply no point trying to assist you here, your code is a train wreck. I can only hope it is never used by anyone else as you imply. I'm also seriously worried at your ability to cogently design a decent DSL given what you believe is worth doing in order to achieve it.

Thanks for the amusement but I can't see any point in further debate.
 
Status
Not open for further replies.