Re: [Tutor] Regarding Exceptions
On Mon, Feb 17, 2014 at 3:29 AM, Khalid Al-Ghamdi emailkg...@gmail.com wrote: Hi, in the following snippet, why is it I don't need to create an Exception object and I can use the class directly in raise my custom exception? here's a new one... i'm going to try to answer this question without working code since everyone has pointed out it won't compile. the OP is simply asking why Exception didn't need to be defined before using, as with all Python variables... IOW, why doesn't it give a NameError exception here? the reason is because Exception is a built-in, meaning that it's C code that's been made available for you before your Python code executes. look: Exception type 'exceptions.Exception' in reality, built-ins are part of a magical module called __builtins__ that's automagically imported for you so that you never have to do it yourself. check this out: __builtins__.Exception type 'exceptions.Exception' you can also find out what all the other built-ins are using dir(): dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',...] hope this helps! --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A computer never does what you want... only what you tell it. +wesley chun : wescpy at gmail : @wescpy Python training consulting : http://CyberwebConsulting.com Core Python books : http://CorePython.com Python blog: http://wescpy.blogspot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On Fri, Feb 21, 2014 at 12:48 PM, wesley chun wes...@gmail.com wrote: in reality, built-ins are part of a magical module called __builtins__ that's automagically imported for you so that you never have to do it yourself. check this out: __builtins__.Exception type 'exceptions.Exception' you can also find out what all the other built-ins are using dir(): dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',...] In __main__, __builtins__ is the __builtin__ module (no s): __builtins__ module '__builtin__' (built-in) I have no idea why. I guess someone thinks this is convenient? In every other pure-Python (not built-in) module, it defaults to the dict of the __builtin__ module: import __builtin__, os os.__builtins__ is vars(__builtin__) True That's the default when a module is executed. However, it's possible to exec and eval code with a custom __builtins__: ns = {'__builtins__': {'msg': 'spam'}} exec 'print msg' in ns spam eval('msg', ns) 'spam' Just don't be deluded into thinking it's possible to sandbox Python like this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On Fri, Feb 21, 2014 at 01:27:55PM -0500, eryksun wrote: On Fri, Feb 21, 2014 at 12:48 PM, wesley chun wes...@gmail.com wrote: in reality, built-ins are part of a magical module called __builtins__ that's automagically imported for you so that you never have to do it yourself. check this out: __builtins__.Exception type 'exceptions.Exception' you can also find out what all the other built-ins are using dir(): dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',...] In __main__, __builtins__ is the __builtin__ module (no s): __builtins__ module '__builtin__' (built-in) Built-ins is confusing. __builtins__ with an S is a special, implementation-specific hack for CPython only, it is *not* part of the language and you should not rely on it. Never use __builtins__, it is considered for internal use only. In Python 2, the built-in objects live inside a module called __builtin__ (with no S). Like all modules, you have to import it before you can access the module. Unlike other modules, it's automatically used to look up names, even if you haven't imported it. So when you refer to a name like foo, or len, or Exception, Python searches the local variables, the global variables, and the built-ins, before raising NameError if it is not found at all. The difference between private __builtins__ and public __builtin__ is confusing and subtle and easy to get wrong, so in Python 3 the built-in module was renamed to builtins. # Don't do this, this is bad. __builtins__.len # Instead, do this in Python 2. import __builtin__ __builtin__.len # Or in Python 3. import builtins builtins.len The history of __builtins__ with an S is quite old. It's used for performance reasons, and originally it was supposed to be used for sandboxing Python, but that turned out to not work. So although it still exists even in Python 3, it's a performance hack for the CPython interpreter, and does not exist in Jython, IronPython or other interpreters. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On Fri, Feb 21, 2014 at 8:50 PM, Steven D'Aprano st...@pearwood.info wrote: The history of __builtins__ with an S is quite old. It's used for performance reasons, and originally it was supposed to be used for sandboxing Python, but that turned out to not work. So although it still exists even in Python 3, it's a performance hack for the CPython interpreter, and does not exist in Jython, IronPython or other interpreters. I can see how it's a small memory optimization to store __builtins__ in globals. Otherwise a function would need another slot for func_builtins, just as a frame has f_globals and f_builtins. That's assuming CPython retains the ability to use a custom builtins namespace. As you say, that isn't even possible in other Python implementations such as Jython. As to this being a performance hack, I can't see how using __builtins__ improves performance, since the interpreter keeps a reference to the dict of the __builtin__ module. The attempt at sandboxing runs deeper than just customizing __builtins__. Search the CPython 2.x source for PyEval_GetRestricted. The latter returns true when a frame's f_builtins isn't the interpreter's builtins. Restricted code can't directly create file objects, unmarshal code objects (from .pyc), set old-style class attributes, or read/write restricted members of built-in objects such as a function's __doc__, among other restrictions. But trying to lock Python down in an otherwise uncontrolled environment is harder than playing Whac-A-Mole. Almost all of the restricted API was removed from Python 3, except for a few legacy flags. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On Mon, Feb 17, 2014 at 12:44 PM, Khalid Al-Ghamdi emailkg...@gmail.com wrote: Hi, Why is it i can use mu custom class exception without creating an exception object first? Thanks class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input() if len(text) 3: raise ShortInputException(len(text), 3) # Other work can continue as usual here except EOFError: print() except ShortInputException as ex: print(\ .format(ex.length, ex.atleast)) else: print() Hello there! Unfortunately, the code you provided is invalid, and it seems not to contain required indentation, newlines, and has some other things that should break (eg. line 12) Please reply (using Reply All!) in plaintext, with the correct code. Also, do you mind phrasing your question more precisely? Do you need help with inheritance? What is the problem you’re having? -- Chris “Kwpolska” Warrick http://kwpolska.tk PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On 17/02/14 11:44, Khalid Al-Ghamdi wrote: Why is it i can use mu custom class exception without creating an exception object first? There are formatting problems when I try to copy your code. I've tried to fix them below, apologies if I got it wrong. However you do create an instance when you raise it... class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input() if len(text) 3: raise ShortInputException(len(text), 3) You have your class name followed by parens. That's how you create an instance. So you are raising an instance of your class. except ShortInputException as ex: print(... And you catch the instance as ex here... But remember that in Python classes are objects too... So you don't always need to create an instance to use a class. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding Exceptions
On 02/17/2014 06:44 AM, Khalid Al-Ghamdi wrote: Hi, Why is it i can use mu custom class exception without creating an exception object first? Thanks 1. class ShortInputException(Exception): def __init__(self, length, atleast): 2. Exception.__init__(self) 3. self.length = length 4. self.atleast = atleast 5. try: 6. text = input() if len(text) 3: 7. raise ShortInputException(len(text), 3) # Other work can continue as usual here 8. except EOFError: 9. print() 10. except ShortInputException as ex: 11. print(\ 12. .format(ex.length, ex.atleast)) else: 13. print() Your code posted here is totally broken. indentation is missing and lines are illegally combined. And somehow you added colors and incorrect line numbers besides. Please post here in plain text, not html, and without line numbers, colorizing or other nonsense. Now to your question. I don't know what you mean without creating an exception object. You create one in the raise statement. It is dubious however to raise an exception in any __init__ routine, since that could perhaps mean that not all the intiialization has actually happened. And it could lead to infinite recursion, if the exception is the same class as you're initializing. I would also strenuously avoid doing input() or other blocking operations in the __init__ routine, but I'm not sure I know of any real reason why. if this is real code, and not just an experiment, could you explain (after formatting it in a text message so we can actually read it) just what does happen, and what you expected/wished to happen? (You might not see this message or my others for quite some time, as it seems I've been dropped from the approved posters by having joined the mailing list ???) -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor