GeneratorExit masks StopIteration?
Does generator.close() prevent raising StopIteration? I'm trying to get the return value from coroutine after terminating it. Here is simple test code: $ python3 Python 3.6.0 (default, Dec 23 2016, 12:50:55) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def cor(): ... try: ... item = yield ... except GeneratorExit: ... return 1 ... >>> c = cor() >>> next(c) >>> c.close() >>> I was expecting StopIteration from c.close() call, but Python 3.6 doesn't raise any. Is this behavior expected? I couldn't find any reference regarding GeneratorExit and StopIteration interaction. -- https://mail.python.org/mailman/listinfo/python-list
Re: GeneratorExit masks StopIteration?
On Sunday, January 29, 2017 at 9:54:44 PM UTC-8, Chris Angelico wrote: > ... > When you close() a generator, it raises GeneratorExit into it, and > then silences any StopIteration or GeneratorExit that comes out of it. Chris, Thanks for the info. Is this (GenExit silencing StopIteration) documented somewhere? I was suspecting this but couldn't find any reference. -- https://mail.python.org/mailman/listinfo/python-list
Re: GeneratorExit masks StopIteration?
On Sunday, January 29, 2017 at 10:47:09 PM UTC-8, Chris Angelico wrote: > On Mon, Jan 30, 2017 at 5:38 PM, wrote: > > On Sunday, January 29, 2017 at 9:54:44 PM UTC-8, Chris Angelico wrote: > >> ... > >> When you close() a generator, it raises GeneratorExit into it, and > >> then silences any StopIteration or GeneratorExit that comes out of it. > > > > Chris, > > Thanks for the info. Is this (GenExit silencing StopIteration) documented > > somewhere? > > I was suspecting this but couldn't find any reference. > > Actually. think this might be incorrect. I didn't look in the > docs, I looked in the source code, so my information is guaranteed > accurate I found PEP-342 describes this behavior - silencing other GenExit or StopIteration. BTW, the reason why I was checking this was to find a solution on how to get return value from coroutine without relying on some sentinel value, something like (not tested): def accumulator(): sum = 0 try: while True: sum += yield except GeneratorExit: return sum Any alternatives? Explicitly throwing GenExit looks like a hack. -- https://mail.python.org/mailman/listinfo/python-list
[OT] Re: how to debug when "Segmentation fault"
On Tue, Oct 04, 2005 at 11:22:24AM -0500, Michael Ekstrand wrote: [...] > I've never seen "stock" Python (stable release w/ only included modules) > segfault, but did see a segfault with an extension module I was using > the other week (lxml IIRC, but I'm not sure). > > - Michael So far, this is the simplest way to crash stock python, at least in Unix/Linux; $ python < /bin If you redirect directory instead of file, python crashes. I think this bug was introduced around 2.1 or 2.2, and not yet fixed as of 2.4.1. - Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: repeating regular expressions in one string
On Wed, Nov 16, 2005 at 03:09:56PM -0500, Shane wrote: > Hi folks, > > I'm new to regular expressions (and a novice at Python) but it seems to be > the tool I need for a particular problem. I have a bunch of strings that > looks like this: > > 'blahblah_sf1234-sf1238_blahblah' > > and I would like to use the re module to parse all the 'sf' parts of the > string. Each 'sf' needs to be its own string when I am through. How do I > compile a regular expression that looks for more than one instance? Currently > my expression looks like this: > > myString = re.compile('sf[0-9][0-9][0-9][0-9]') > > This works great for finding the first instance of 'sf'. I hope that was > clear :) > > Thanks, > > Shane > -- > http://mail.python.org/mailman/listinfo/python-list You can simplify your pattern myString = re.compile('sf[0-9][0-9][0-9][0-9]') to myString = re.compile(r"sf\d{4}") >>> import re >>> s = 'blahblah_sf1234-sf1238_blahblah' >>> pat = re.compile(r"sf\d{4}") >>> re.findall(pat, s) ['sf1234', 'sf1238'] >>> for m in re.finditer(pat, s): ... print m.group() ... sf1234 sf1238 >>> Inyeol -- http://mail.python.org/mailman/listinfo/python-list
[pyparsing] How to get arbitrary text surrounded by keywords?
I'm trying to extract module contents from Verilog, which has the form of; module foo (port1, port2, ... ); // module contents to extract here. ... endmodule To extract the module contents, I'm planning to do something like; from pyparsing import * ident = Word(alphas+"_", alphanums+"_") module_begin = Group("module" + ident + "(" + OneOrMore(ident) + ")" + ";") module_contents = ??? module_end = Keyword("endmodule") module = Group(module_begin + module_contents + module_end) (abobe code not tested.) How should I write the part of 'module_contents'? It's an arbitrary text which doesn't contain 'endmodule' keyword. I don't want to use full scale Verilog parser for this task. -Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: [pyparsing] How to get arbitrary text surrounded by keywords?
On Mon, Nov 28, 2005 at 09:00:58PM +, Paul McGuire wrote: > "Inyeol Lee" <[EMAIL PROTECTED]> wrote in message > [...] > > How should I write the part of 'module_contents'? It's an arbitrary text > > which doesn't contain 'endmodule' keyword. I don't want to use full > > scale Verilog parser for this task. > > > > -Inyeol > > The simplest way is to use SkipTo. This only works if you don't have to > worry about nesting. I think Verilog supports nested modules, but if the > files you are parsing don't use this feature, then SkipTo will work just > fine. > > module_begin = Group("module" + ident + "(" + OneOrMore(ident) + ")" + ";") > module_end = Keyword("endmodule") > module_contents = SkipTo(module_end) > > If you *do* care about nested modules, then a parse action might help you > handle these cases. But this starts to get trickier, and you may just want > to consider a more complete grammar. If your application is non-commercial > (i.e., for academic or personal use), there *is* a full Verilog grammar > available (also available with commercial license, just not free). > > -- Paul Thanks Paul. 'SkipTo' is what I was looking for. -Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Instances behaviour
On Thu, Dec 01, 2005 at 03:51:05PM -0800, Mr.Rech wrote: [...] > Suppose I have a bunch of classes that represent slightly (but > conceptually) different object. The instances of each class must behave > in very similar manner, so that I've created a common class ancestor > (let say A) that define a lot of special method (such as __getattr__, > __setattr__, __len__ and so on), and then I've created all my "real" > classes inheriting from it: > > >>>class A(object): > # here define all special and some common methods > > >>> class B(A): > # this is the first "real" class > > >>> class C(A): > # and this is the second > > and so on. The problem I'm worried about is that an unaware user may > create an instance of "A" supposing that it has any real use, while it > is only a sort of prototype. However, I can't see (from my limited > point of view) any other way to rearrange things and still get a > similar behaviour. >>> class A(object): >>> ... def __init__(self, foo): >>> ... if self.__class__ is A: >>> ... raise TypeError("A is base class.") >>> ... self.foo = foo >>> ... >>> class B(A): ... pass ... >>> class C(A): ... def __init__(self, foo, bar): ... A.__init__(self, foo) ... self.bar = bar ... >>> a = A(1) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ TypeError: A is base class. >>> b = B(1) >>> b.foo 1 >>> c = C(1, 2) >>> c.foo, c.bar (1, 2) >>> HTH --Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: Instances behaviour
On Fri, Dec 02, 2005 at 10:43:56AM +0100, bruno at modulix wrote: > Inyeol Lee wrote: > (snip) > > >>>>class A(object): > >>>>... def __init__(self, foo): > >>>>... if self.__class__ is A: > >>>>... raise TypeError("A is base class.") > > > s/TypeError/NotImplementedError/ > s/base class/abstract class/ I prefer TypeError here, NotImplementedError would be OK though. Here is an example from sets.py in stdlib. class BaseSet(object): """Common base class for mutable and immutable sets.""" __slots__ = ['_data'] # Constructor def __init__(self): """This is an abstract class.""" # Don't call this from a concrete subclass! if self.__class__ is BaseSet: raise TypeError, ("BaseSet is an abstract class. " "Use Set or ImmutableSet.") Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
On Fri, Dec 02, 2005 at 09:45:10PM +0100, Gerhard H�ring wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > Micah Elliott wrote: > > On Dec 02, Dave Hansen wrote: > > > >>Python recognizes the TAB character as valid indentation. TAB > >>characters are evil. They should be banned from Python source code. > > > > AGREE! AGREE! AGREE! > > > >>The interpreter should stop translation of code and throw an > >>exception when one is encountered. > > > > > > You could file a "Parser/Compiler" Feature Request for this [...] > > Read PEP 666 first. > And this one too ;-) http://www.artima.com/weblogs/viewpost.jsp?thread=101968 --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting PYTHONPATH from Makefile
On Fri, Dec 02, 2005 at 07:33:20PM -0500, Mike Meyer wrote: > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > > I have a Makefile target that uses a python script, like: > > > > %.abc: %.def > > python myscript.py > > > > The problem is that myscript.py and some modules that myscript.py > > imports are not in the current directory, but in another place in the > > filesystem, say, /path/to/stuff. If this was a tcsh script, I would > > just do: > > > >setenv PYTHONPATH /path/to/stuff > >python myscript.py > > And that still wouldn't work, because you said that myscript.py wasn't > in the current directory either. > > > but this cannot be done from a Makefile. So what do I do? Is there > > another way to set the PYTHONPATH? Like giving an option to "python" > > itself? Or? > > No, you can't. You have to tweak the makefile. Try: > > %.abc: %.def >(cd /path/to/myscripts/dir; python myscript.py) > > > N.B. - this probably depends on both the system and the make you're > using. > How about using python -m? Assuming Make uses Bourne shell, %.abc: %.def PYTHONPATH=/path/to/stuff:/path/to/another python -m myscript Don't forget to strip '.py' extension. --Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting PYTHONPATH from Makefile
On Fri, Dec 02, 2005 at 08:10:41PM -0500, Mike Meyer wrote: > Inyeol Lee <[EMAIL PROTECTED]> writes: > > On Fri, Dec 02, 2005 at 07:33:20PM -0500, Mike Meyer wrote: > >> > The problem is that myscript.py and some modules that myscript.py > >> > imports are not in the current directory, but in another place in the > >> > filesystem, say, /path/to/stuff. If this was a tcsh script, I would > >> > just do: > >> > > >> >setenv PYTHONPATH /path/to/stuff > >> >python myscript.py > > How about using python -m? > > Assuming Make uses Bourne shell, > > > > %.abc: %.def > > PYTHONPATH=/path/to/stuff:/path/to/another python -m myscript > > That will break __name__ (at least with 2.4.2). Whether or not it > matters will depend on the script. > $ python -V Python 2.4.2 $ cat foo/bar.py print __name__ $ (cd foo; python bar.py) __main__ $ PYTHONPATH=$PWD/foo python -m bar __main__ $ Am I missing something? I don't see any issue regarding __name__. -- Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
smtpd.py in python2.4/bin directory?
After installing Python 2.4 from src tarball I found one new executable in python/bin directory - "smtpd.py". I also found the same file in python/lib/python2.4/. Is this intentional or just a minor bug in build script? Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring variables from a list
On Sat, Apr 09, 2005 at 03:15:01AM +0530, Sidharth Kuruvila wrote: > Python has a builtin function called locals which returns the local > context as a dictionary > > >>> locals = locals() > >>> locals["a"] = 5 > >>> a > 5 > >>> locals["a"] = "changed" > >>> a > 'changed' >From Python lib reference: """ locals() ... Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance?
On Wed, Aug 16, 2006 at 11:07:08AM -0700, KraftDiner wrote: [...] > Here I tried this example and maybe this will explain the difficulties > I'm having. > 1) at the time the baseClass is constructed shouldn't the constructor > of the appropriate > type be called. > 2) getName is doing nothing... > > class baseClass: > def __init__(self): > pass > def fromfile(self, str): > if (str == 'A'): > a = typeA() > else: > a = typeB() > def getName(self): > pass > > class typeA(baseClass): > def __init__(self): > self.name='A' > print 'typeA init' > def fromfile(self, str=None): > print 'typeA fromfile' > def getName(self): > print self.name > > class typeB(baseClass): > def __init__(self): > self.name='B' > print 'typeB init' > def fromfile(self, str=None): > print 'typeB fromfile' > def getName(self): > print self.name > > bc = baseClass() > bc.fromfile('A') > bc.getName() > bc.fromfile('B') > bc.getName() > bc.getName() > > log: > typeA init > typeB init > I didn't follow up this thread from the begining, but I think this is what you want; Python 2.4.3 (#1, Mar 31 2006, 09:09:53) [GCC 2.95.3 20010315 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> class baseClass: ... @staticmethod ... def fromfile(string): ... if string == "A": ... return typeA() ... else: ... return typeB() ... def getName(self): ... print self.name ... >>> class typeA(baseClass): ... def __init__(self): ... self.name = "A" ... print "typeA init" ... >>> class typeB(baseClass): ... def __init__(self): ... self.name = "B" ... print "typeB init" ... >>> a = baseClass.fromfile("A") typeA init >>> a.getName() A >>> b = baseClass.fromfile("B") typeB init >>> b.getName() >>> B >>> -- Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: scared about refrences...
On Wed, Nov 01, 2006 at 12:20:36PM -0800, SpreadTooThin wrote: > > Bruno Desthuilliers wrote: > > Nick Vatamaniuc a �crit : > > (snip) > > > In Python all the primitives are copied and all other entities are > > > references. > > > > Plain wrong. There's no "primitives" (ie : primitive data types) in > > Python, only objects. And they all get passed the same way. > > so.. > def fn(x): >x = x + 1 >print x > > a = 2 > fn(a) > fn(2) > > Wouldn't you say that this is being passed by value rather than by > refrence? > What you're confused with is assignment. Check this example; >>> def f(x): ... print id(x) ... x = x + 1 ... print id(x) ... >>> f(1234) 1617596 1617608 >>> a = 5678 >>> id(a) 1617596 >>> f(a) 1617596 1617620 >>> You can assume id() as a memory address. Is it call-by-value? -- Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange behavior with iterables - is this a bug?
On Tue, May 30, 2006 at 01:11:26PM -0700, [EMAIL PROTECTED] wrote: [...] > >>> RESTART > >>> f1 = open('word1.txt') > >>> f2 = open('word2.txt') > >>> f3 = open('word3.txt') > >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 for > >>> i3 in f3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] > >>> l1 = ['a\n','b\n','c\n'] > >>> l2 = ['a\n','b\n','c\n'] > >>> > >>> l3 = ['a\n','b\n','c\n'] > >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for > >>> i3 in l3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), > ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), > ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), > ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), > ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), > ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), > ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')] > > explanation of code: the files word1.txt, word2.txt and word3.txt are > all identical conataining the letters a,b and c one letter per line. > The lists I've added the "\n" so that the lists are identical to what > is returned by the file objects. Just eliminating any possible > differences. You're comparing file, which is ITERATOR, and list, which is ITERABLE, not ITERATOR. To get the result you want, use this instead; >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in open('word1.txt') for i2 in open('word2.txt') for i3 in open('word3.txt')] FIY, to get the same buggy(?) result using list, try this instead; >>> l1 = iter(['a\n','b\n','c\n']) >>> l2 = iter(['a\n','b\n','c\n']) >>> l3 = iter(['a\n','b\n','c\n']) >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 >>> in l3] [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] >>> -Inyeol Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: Best place for a function?
On Wed, Mar 07, 2007 at 05:27:04PM -0500, Sergio Correia wrote: > I'm writing a class, where one of the methods is kinda complex. The > method uses a function which I know for certain will not be used > anywhere else. This function does not require anything from self, only > the args passed by the method. > > Where should I put the function? Use staticmethod. It's a normal function with class namespace. --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Best place for a function?
On Sun, Mar 11, 2007 at 06:36:02PM +0100, Bruno Desthuilliers wrote: > Inyeol Lee a �crit : > > On Wed, Mar 07, 2007 at 05:27:04PM -0500, Sergio Correia wrote: > > > >>I'm writing a class, where one of the methods is kinda complex. The > >>method uses a function which I know for certain will not be used > >>anywhere else. This function does not require anything from self, only > >>the args passed by the method. > >> > >>Where should I put the function? > > > > > > Use staticmethod. It's a normal function with class namespace. > > What do you think the OP will gain from making a simple helper function > a staticmethod ? Apart from extra lookup time ? Namespace. Plz check this old thread. It explains some usage of staticmethod. http://mail.python.org/pipermail/python-list/2003-February/190258.html --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: tabs and spaces in py3k
On Dec 7, 8:51 pm, [EMAIL PROTECTED] wrote: > The following code works under 2.6 > > def foo(): > a = 1 > <.tab..>b = 1 > > but results in a TabError in Python 3k > > File "x.py", line 3 > b = 3 > ^ > TabError: inconsistent use of tabs and spaces in indentation > > The py3k docs say the same thing as the 2.6 docs, > namely that tabs are expanded to spaces prior to > determining the line's indentation. (Language > Ref, Lex Anal, Line Struct, Indentation) > (I wish someone would put the section numbers > back in the docs.) No mention of this change > (that I noticed) in What's New or NEWS.txt. > > Do the Py3k docs need correction? -tt option in python 2.x is now default in python 3.0. Apparently it got slipped from any documentation, including what's new. --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 __cmp__ semantic change?
On Nov 20, 1:18 pm, Johannes Bauer <[EMAIL PROTECTED]> wrote: > Hello group, > > I'm porting some code of mine to Python 3. One class has the __cmp__ > operator overloaded, but comparison doesn't seem to work anymore with that: > > Traceback (most recent call last): > File "./parse", line 25, in > print(x < y) > TypeError: unorderable types: IP() < IP() > > Was there some kind of semantic change? Overload __lt__ method. Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I tell "imconplete input" from "valid input"?
On May 29, 9:26 am, たか <[EMAIL PROTECTED]> wrote: > Hi everyone, > > I am developing the console which has the embedded Python interactive > interpreter. So, I want to judge whether current command is complete > or not. Below is good example to solve this problem. > // > //http://effbot.org/pyfaq/how-do-i-tell-incomplete-input-from-invalid-i... > // > int testcomplete(char *code) > /* code should end in \n */ > /* return -1 for error, 0 for incomplete, 1 for complete */ > { > node *n; > perrdetail e; > > n = PyParser_ParseString(code, &_PyParser_Grammar, >Py_file_input, &e); > if (n == NULL) { > if (e.error == E_EOF) > return 0; > return -1; > } > > PyNode_Free(n); > return 1; > > } > > But, I think this code has a problem. For example, when argument > 'code' has below python command, > > if x % 2: >print "odd" > > at the current situation, this function returns COMPLETE! > But, I think that sometimes users want to type "else" statement. So, I > expected to get INCOMPLETE from this function, but I didn't. > > How should I do it? > > Thanks, > urai I guess you should use "Py_single_input" instead of "Py_file_input" in your code, which requires extra NEWLINE to end complex statement. Plz check details in Grammar/Grammar from python source distribution --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: How to serialize and deserialize the objects into memory?
On Jul 11, 12:58 pm, hardemr <[EMAIL PROTECTED]> wrote: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? pickle.dumps and pickle.loads. --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: unix newbie questions
On Sat, Mar 25, 2006 at 03:45:56AM -0800, Gerard Flanagan wrote: [...] > * If I want to do : > > mv mypackage-1.0.2.tar.gz subdir/mypackage-1.0.2.tar.gz > > then tab-completion gives me the first occurrence of the file, but I > have to type the second occurrence - is there a way of not having to > type it? In this specific case you don't need second filename. mv mypackage-1.0.2.tar.gz subdir/ is enough. If you need filename for some reason, use this. mv mypackage-1.0.2.tar.gz subdir/mypackage-1.0.2.tar.gz.backup => mv mypackage-1.0.2.tar.gz subdir/!#:1.backup This works for both bash and (t)csh. --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope (?) question
On Jun 15, 3:22 pm, Peter wrote: > I am puzzled by what appears to be a scope issue - obviously I have > something wrong :-) > > Why does this work: > > if __name__ == 'main': > execfile('test-data.py') > print data > > and yet this doesn't (I get "NameError: global name 'data' not > defined"): > > def X(): > execfile('test-data.py') > print data > > where test-data.py is: > > data = [1,2,3,4] > > I checked help on execfile and could only find the following > (mystifying) sentence: > > "execfile() cannot be used reliably to modify a function’s locals." > > Thanks > Peter This is due to CPython's static optimization of local name lookup. Dummy 'exec' statement disables this and makes your example work: def X(): exec "None" execfile('test-data.py') print data --inyeol -- http://mail.python.org/mailman/listinfo/python-list