From tk446 at snu.edu.in Wed Oct 1 12:37:02 2014 From: tk446 at snu.edu.in (Tarun Kumar) Date: Wed, 1 Oct 2014 16:07:02 +0530 Subject: [BangPypers] Python for RTOS Message-ID: Hello all Greetings from my side. I am working with ARM 9 + embOS(RTOS) + Emfile(file system) and I need a Python interpreter over it. can you guys help me with name of the Python interpreter. For example I was wondering whether PyMite will work with my board or not. I can find all compatibility issues online but unable to find suitability of embOS(RTOS by segger) with python interpreter. Thanks and regards -- -Tarun Kumar Shiv Nadar University ---------------------------------------- From vidhishanair at gmail.com Wed Oct 1 16:46:24 2014 From: vidhishanair at gmail.com (vidhisha nair) Date: Wed, 1 Oct 2014 20:16:24 +0530 Subject: [BangPypers] Invitation to deliver workshop at PyCampus at PES Institute of Technology Message-ID: Hello all! I'm Vidhisha, a final year student from PES Institute of Technology, Bangalore and a member of the PES Open Source Community [1]. We are a strong community of 5000+ members based out of PES Institute to Technology. We actively advocate, evangelize and spread the message on being open. We help beginners get started with contributing to Open Source. As part of our activities, we plan to have a Python Workshop 'PyCampus' at our college for the benefit of our students, so that they can be aware of the power and use of the language. We would like to have a beginners day of Python on 19th October, 2014 where we would like all basics of python to be taught and an advanced day on 2nd November, 2014 where we look into advanced applications of python like Pandas, Flask, etc. We had collaborated with the Bangalore Python Users Group last year for the same event and had an amazing feedback from our students and community. We would like to request members of this community to once again come in as speakers for these days so that we can deliver an amazing session to students at our college. Please feel free to ask me any further details which I have missed out. You can contact me on: vidhishanair at gmail.com 7899364937 [1] PES Open Source Community : http://pesos.pes.edu/ https://www.facebook.com/groups/pesosc/ -- Thanks and Regards, Vidhisha B PES Open Source Community From vsapre80 at gmail.com Wed Oct 1 19:02:21 2014 From: vsapre80 at gmail.com (Vishal) Date: Wed, 1 Oct 2014 22:32:21 +0530 Subject: [BangPypers] Python for RTOS In-Reply-To: References: Message-ID: Dear Tarun, your best bet in this case is the support from Segger. I am sure someone before must have used Python on embOS. Atleast they can help you compile it for the OS from python source. Take care, Vishal Sapre Thanks and best regards, Vishal Sapre --- Please DONT print this email, unless you really need to. Save Energy & Paper. Save the Earth. On Wed, Oct 1, 2014 at 4:07 PM, Tarun Kumar wrote: > Hello all > Greetings from my side. > I am working with ARM 9 + embOS(RTOS) + Emfile(file system) and I need a > Python interpreter over it. can you guys help me with name of the Python > interpreter. For example I was wondering whether PyMite will work with my > board or not. I can find all compatibility issues online but unable to find > suitability of embOS(RTOS by segger) with python interpreter. > > > > Thanks and regards > -- > > -Tarun Kumar > Shiv Nadar University > ---------------------------------------- > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > From tk446 at snu.edu.in Wed Oct 1 19:21:20 2014 From: tk446 at snu.edu.in (Tarun Kumar) Date: Wed, 1 Oct 2014 22:51:20 +0530 Subject: [BangPypers] Python for RTOS In-Reply-To: References: Message-ID: Dear Vishal I have sent an email to segger regarding same. Thanks for your support. best Tarun On Wed, Oct 1, 2014 at 10:32 PM, Vishal wrote: > Dear Tarun, > > your best bet in this case is the support from Segger. I am sure someone > before must have used Python on embOS. > Atleast they can help you compile it for the OS from python source. > > Take care, > Vishal Sapre > > > > Thanks and best regards, > Vishal Sapre > > --- > Please DONT print this email, unless you really need to. Save Energy & > Paper. Save the Earth. > > On Wed, Oct 1, 2014 at 4:07 PM, Tarun Kumar wrote: > > > Hello all > > Greetings from my side. > > I am working with ARM 9 + embOS(RTOS) + Emfile(file system) and I need a > > Python interpreter over it. can you guys help me with name of the Python > > interpreter. For example I was wondering whether PyMite will work with my > > board or not. I can find all compatibility issues online but unable to > find > > suitability of embOS(RTOS by segger) with python interpreter. > > > > > > > > Thanks and regards > > -- > > > > -Tarun Kumar > > Shiv Nadar University > > ---------------------------------------- > > _______________________________________________ > > BangPypers mailing list > > BangPypers at python.org > > https://mail.python.org/mailman/listinfo/bangpypers > > > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- -Tarun Kumar Shiv Nadar University ---------------------------------------- From rajiv.m1991 at gmail.com Thu Oct 2 12:21:41 2014 From: rajiv.m1991 at gmail.com (Rajiv Subramanian M) Date: Thu, 2 Oct 2014 15:51:41 +0530 Subject: [BangPypers] Python List Comprehension Question Message-ID: Hello Group, I'm Rajiv working as web developer in bangalore. Objective: We need to convert the list containing integers and nested list of integer in it e.g.) x = [[1, 2, [3]], 4] into a flat list format e.g.) result = [1, 2, 3, 4] MyAnswer using Recursive function: def flat_it(List): result = [] for item in List: if type(item) is int: result.append(item) else: result += flat_it(item) return result print flat_it(x) This actually works, but I tried to optimize this with List comprehension like the following code, but it never worked def flat_it(List): return [item if type(item) is int else flat_it(item) for item in List] print flat_it(x) This returns result without flatting like what i passed in argument [[1, 2, [3]], 4] please help. -- [image: --] Rajiv Subramanian M [image: http://]about.me/rajiv.m1991 From anandology at gmail.com Thu Oct 2 12:57:31 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Thu, 2 Oct 2014 16:27:31 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M wrote: > Hello Group, > > I'm Rajiv working as web developer in bangalore. > > Objective: > We need to convert the list containing integers and nested list of integer > in it > e.g.) x = [[1, 2, [3]], 4] > into a flat list format > e.g.) result = [1, 2, 3, 4] > > MyAnswer using Recursive function: > def flat_it(List): > result = [] > for item in List: > if type(item) is int: > result.append(item) > else: > result += flat_it(item) > return result > print flat_it(x) > > This actually works, but I tried to optimize this with List comprehension > like the following code, but it never worked > > def flat_it(List): > return [item if type(item) is int else flat_it(item) for item in List] > print flat_it(x) > > This returns result without flatting like what i passed in argument [[1, 2, > [3]], 4] > List comprehensions take a list and return a list of the same size (if you don't use if condition). What you have done is correct solution, though it could be slightly improved like the following: def flat_it(values, result=None): if result is None: result = [] for v in values: if isinstance(v, list): flat_it(v, result) else: result.append(v) return result Improvements: * using isinstance is better than comparing type. * avoids creation of intermediate lists by passing the result along the recursive calls Anand From kracethekingmaker at gmail.com Thu Oct 2 13:45:41 2014 From: kracethekingmaker at gmail.com (kracekumar ramaraju) Date: Thu, 2 Oct 2014 17:15:41 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: Hi `yield from ` is introduced in Python 3.3 as part of pep 380. # python 3.3 from collections import Iterable def flatten(items): for item in items: if isinstance(item, Iterable): yield from flatten(item) else: yield item list(flatten([[1, 2, [3]], 4])) [1, 2, 3, 4] # python 2.7 from collections import Iterable x = [[1, 2, [3]], 4] def flatten(items): for item in items: if isinstance(item, Iterable): for subitem in flatten(item): yield subitem else: yield item ....: list(flatten(x)) [1, 2, 3, 4] PEP 0380: http://legacy.python.org/dev/peps/pep-0380/ P.S: The above approach is discussed in Python 3 CookBook by David Beazley. On Thu, Oct 2, 2014 at 4:27 PM, Anand Chitipothu wrote: > On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M > > wrote: > > > Hello Group, > > > > I'm Rajiv working as web developer in bangalore. > > > > Objective: > > We need to convert the list containing integers and nested list of > integer > > in it > > e.g.) x = [[1, 2, [3]], 4] > > into a flat list format > > e.g.) result = [1, 2, 3, 4] > > > > MyAnswer using Recursive function: > > def flat_it(List): > > result = [] > > for item in List: > > if type(item) is int: > > result.append(item) > > else: > > result += flat_it(item) > > return result > > print flat_it(x) > > > > This actually works, but I tried to optimize this with List comprehension > > like the following code, but it never worked > > > > def flat_it(List): > > return [item if type(item) is int else flat_it(item) for item in List] > > print flat_it(x) > > > > This returns result without flatting like what i passed in argument [[1, > 2, > > [3]], 4] > > > > List comprehensions take a list and return a list of the same size (if you > don't use if condition). > > What you have done is correct solution, though it could be slightly > improved like the following: > > def flat_it(values, result=None): > if result is None: > result = [] > > for v in values: > if isinstance(v, list): > flat_it(v, result) > else: > result.append(v) > return result > > Improvements: > * using isinstance is better than comparing type. > * avoids creation of intermediate lists by passing the result along the > recursive calls > > Anand > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com * From abhishekl.2006 at gmail.com Thu Oct 2 15:04:44 2014 From: abhishekl.2006 at gmail.com (Abhishek L) Date: Thu, 2 Oct 2014 18:34:44 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 5:15 PM, kracekumar ramaraju wrote: > Hi > > `yield from ` is introduced in Python 3.3 as part of pep 380. > > # python 3.3 > > from collections import Iterable > > def flatten(items): > for item in items: > if isinstance(item, Iterable): > yield from flatten(item) > else: > yield item Yield from approach is great if you're using python 3.3+ :) > > list(flatten([[1, 2, [3]], 4])) > [1, 2, 3, 4] > > # python 2.7 > > from collections import Iterable > > x = [[1, 2, [3]], 4] > > def flatten(items): > for item in items: > if isinstance(item, Iterable): > for subitem in flatten(item): > yield subitem > else: > yield item > ....: > > list(flatten(x)) > [1, 2, 3, 4] Also you may need to check whether the item is not a string or bytes or a string in the list will break this, an isinstance(item, Iterable) and not isinstance(item,str) # maybe bytes too should handle that -- Abhishek From kracethekingmaker at gmail.com Thu Oct 2 15:22:29 2014 From: kracethekingmaker at gmail.com (kracekumar ramaraju) Date: Thu, 2 Oct 2014 18:52:29 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 6:34 PM, Abhishek L wrote: > On Thu, Oct 2, 2014 at 5:15 PM, kracekumar ramaraju > wrote: > > Hi > > > > `yield from ` is introduced in Python 3.3 as part of pep 380. > > > > # python 3.3 > > > > from collections import Iterable > > > > def flatten(items): > > for item in items: > > if isinstance(item, Iterable): > > yield from flatten(item) > > else: > > yield item > > Yield from approach is great if you're using python 3.3+ :) > > > > > list(flatten([[1, 2, [3]], 4])) > > [1, 2, 3, 4] > > > > # python 2.7 > > > > from collections import Iterable > > > > x = [[1, 2, [3]], 4] > > > > def flatten(items): > > for item in items: > > if isinstance(item, Iterable): > > for subitem in flatten(item): > > yield subitem > > else: > > yield item > > ....: > > > > list(flatten(x)) > > [1, 2, 3, 4] > > Also you may need to check whether the item is not a string or bytes > or a string in the list will break this, an > > isinstance(item, Iterable) and not isinstance(item,str) # maybe bytes too > > ah, Yes that is correct. Probably flatten can take ignore_types as an argument. condition can be isinstance(item, Iterable) and not isinstance(item, ignore_types) should handle that > > -- > Abhishek > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com * From rajiv.m1991 at gmail.com Thu Oct 2 20:41:18 2014 From: rajiv.m1991 at gmail.com (Rajiv Subramanian M) Date: Fri, 3 Oct 2014 00:11:18 +0530 Subject: [BangPypers] Python List Comprehension Question Message-ID: Hi Krace, I believe as your code returns a generator instance it must be efficient in handling large input as well. And as you said in previous reply I've added "not isinstance(item, (str, bytes))", the code looks like def flat_it(items): for item in items: if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): for subitem in flat_it(item): yield subitem else: yield item and it works fine. But is there any possibilities to use "List Comprehension" methodology ? def flat_it(items): return [item for item in items if not isinstance(item, Iterable) *else flat_it(item)*] The above solution should be possible, but unfortunately list comprehension syntax dosen't allows an extra else condition (mentioned in bold letters above). -- [image: --] Rajiv Subramanian M [image: http://]about.me/rajiv.m1991 From noufal at nibrahim.net.in Thu Oct 2 10:56:16 2014 From: noufal at nibrahim.net.in (Noufal Ibrahim KV) Date: Thu, 02 Oct 2014 14:26:16 +0530 Subject: [BangPypers] Return values In-Reply-To: (Saager Mhatre's message of "Wed, 24 Sep 2014 23:02:25 -0400") References: <87ioki7jda.fsf@nibrahim.net.in> <87wq8y5zrg.fsf@nibrahim.net.in> Message-ID: <87h9zmu9xr.fsf@nibrahim.net.in> On Thu, Sep 25 2014, Saager Mhatre wrote: [...] > Alternatively, would it be possible to model Stats/StatsList as a composite > hierarchy (potentially with Courtesy Implementations > )? [...] I didn't know about Courtesy implementations till now. Thanks. I'm not really convinced with Fowlers argument and I didn't like the solution but it's still an interesting patterns. -- Cordially, Noufal http://nibrahim.net.in From noufal at nibrahim.net.in Thu Oct 2 10:56:21 2014 From: noufal at nibrahim.net.in (Noufal Ibrahim KV) Date: Thu, 02 Oct 2014 14:26:21 +0530 Subject: [BangPypers] Return values In-Reply-To: (Saager Mhatre's message of "Wed, 24 Sep 2014 23:02:25 -0400") References: <87ioki7jda.fsf@nibrahim.net.in> <87wq8y5zrg.fsf@nibrahim.net.in> Message-ID: <87eguqu9xm.fsf@nibrahim.net.in> On Thu, Sep 25 2014, Saager Mhatre wrote: [...] > Alternatively, would it be possible to model Stats/StatsList as a composite > hierarchy (potentially with Courtesy Implementations > )? [...] I didn't know about Courtesy implementations till now. Thanks. I'm not really convinced with Fowlers argument and I didn't like the solution but it's still an interesting pattern. -- Cordially, Noufal http://nibrahim.net.in From bhargav.kowshik at yahoo.com Fri Oct 3 16:56:33 2014 From: bhargav.kowshik at yahoo.com (Bhargav Kowshik) Date: Fri, 3 Oct 2014 14:56:33 +0000 (UTC) Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: <2022172401.234739.1412348193736.JavaMail.yahoo@jws10001g.mail.ne1.yahoo.com> We could use what Anand talked about at Pycon India about handling the headers in first row of a CSV.In this scenario, instead of default for result being None and checking if None everytime, we could have the default value an empty list. def flat_it(values, result=list()): ??? for v in values: ??????? if isinstance(v, list): ??????????? flat_it(v, result) ??????? else: ??????????? result.append(v) ??? return result x = [[1, 2, [3, 4, 5, 6, 7]], 4] print x print flat_it(x) ?Thank you, Bhargav. On Thursday, October 2, 2014 4:27 PM, Anand Chitipothu wrote: On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M wrote: > Hello Group, > > I'm Rajiv working as web developer in bangalore. > > Objective: > We need to convert the list containing integers and nested list of integer > in it > e.g.) x = [[1, 2, [3]], 4] > into a flat list format > e.g.) result = [1, 2, 3, 4] > > MyAnswer using Recursive function: > def flat_it(List): >? ? result = [] >? ? for item in List: >? ? ? ? if type(item) is int: >? ? ? ? ? ? result.append(item) >? ? ? ? else: >? ? ? ? ? ? result += flat_it(item) >? ? return result > print flat_it(x) > > This actually works, but I tried to optimize this with List comprehension > like the following code, but it never worked > > def flat_it(List): > return [item if type(item) is int else flat_it(item) for item in List] > print flat_it(x) > > This returns result without flatting like what i passed in argument [[1, 2, > [3]], 4] > List comprehensions take a list and return a list of the same size (if you don't use if condition). What you have done is correct solution, though it could be slightly improved like the following: def flat_it(values, result=None): ? ? if result is None: ? ? ? ? result = [] ? ? for v in values: ? ? ? ? if isinstance(v, list): ? ? ? ? ? ? flat_it(v, result) ? ? ? ? else: ? ? ? ? ? ? result.append(v) ? ? return result Improvements: * using isinstance is better than comparing type. * avoids creation of intermediate lists by passing the result along the recursive calls Anand _______________________________________________ BangPypers mailing list BangPypers at python.org https://mail.python.org/mailman/listinfo/bangpypers From anandology at gmail.com Fri Oct 3 17:18:02 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Fri, 3 Oct 2014 20:48:02 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: <2022172401.234739.1412348193736.JavaMail.yahoo@jws10001g.mail.ne1.yahoo.com> References: <2022172401.234739.1412348193736.JavaMail.yahoo@jws10001g.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 3, 2014 at 8:26 PM, Bhargav Kowshik < bhargav.kowshik at yahoo.com.dmarc.invalid> wrote: > We could use what Anand talked about at Pycon India about handling the > headers in first row of a CSV.In this scenario, instead of default for > result being None and checking if None everytime, we could have the default > value an empty list. > > def flat_it(values, result=list()): > for v in values: > if isinstance(v, list): > flat_it(v, result) > else: > result.append(v) > return result > > x = [[1, 2, [3, 4, 5, 6, 7]], 4] > print x > print flat_it(x) > Thats a pitfall! Try calling flat_it once again and see what you get. Anand From bhargav.kowshik at yahoo.com Fri Oct 3 17:34:39 2014 From: bhargav.kowshik at yahoo.com (Bhargav Kowshik) Date: Fri, 3 Oct 2014 15:34:39 +0000 (UTC) Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: <803376319.247924.1412350479548.JavaMail.yahoo@jws10032.mail.ne1.yahoo.com> Nice! Thank you very much Anand.But, I still don't know what is happening.Please point me to a resource to understand what is happening. ** Program ** def flat_it(values, result=list()): ??? for v in values: ??????? if isinstance(v, list): ??????????? flat_it(v, result) ??????? else: ??????????? result.append(v) ??? return result x = [[1, 2, [3, 7]], 4] print('Input: {0}'.format(x)) print('Output 1: {0}'.format(flat_it(x))) print('Output 2: {0}'.format(flat_it(x))) print('Output 3: {0}'.format(flat_it(x, list()))) ** Output ** Input: [[1, 2, [3, 7]], 4] Output 1: [1, 2, 3, 7, 4] Output 2: [1, 2, 3, 7, 4, 1, 2, 3, 7, 4] Output 3: [1, 2, 3, 7, 4] Thank you, Bhargav. On Friday, October 3, 2014 8:48 PM, Anand Chitipothu wrote: On Fri, Oct 3, 2014 at 8:26 PM, Bhargav Kowshik wrote: We could use what Anand talked about at Pycon India about handling the headers in first row of a CSV.In this scenario, instead of default for result being None and checking if None everytime, we could have the default value an empty list. def flat_it(values, result=list()): ??? for v in values: ??????? if isinstance(v, list): ??????????? flat_it(v, result) ??????? else: ??????????? result.append(v) ??? return result x = [[1, 2, [3, 4, 5, 6, 7]], 4] print x print flat_it(x) Thats a pitfall! Try calling flat_it once again and see what you get. Anand From kracethekingmaker at gmail.com Fri Oct 3 17:48:03 2014 From: kracethekingmaker at gmail.com (kracekumar ramaraju) Date: Fri, 3 Oct 2014 21:18:03 +0530 Subject: [BangPypers] Python List Comprehension Question In-Reply-To: <803376319.247924.1412350479548.JavaMail.yahoo@jws10032.mail.ne1.yahoo.com> References: <803376319.247924.1412350479548.JavaMail.yahoo@jws10032.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 3, 2014 at 9:04 PM, Bhargav Kowshik < bhargav.kowshik at yahoo.com.dmarc.invalid> wrote: > Nice! Thank you very much Anand.But, I still don't know what is > happening.Please point me to a resource to understand what is happening. > > A common beginner mistake. More of such gotcha can be found here http://docs.python-guide.org/en/latest/writing/gotchas/ . > ** Program ** > > def flat_it(values, result=list()): > for v in values: > if isinstance(v, list): > flat_it(v, result) > else: > result.append(v) > return result > > x = [[1, 2, [3, 7]], 4] > > print('Input: {0}'.format(x)) > print('Output 1: {0}'.format(flat_it(x))) > print('Output 2: {0}'.format(flat_it(x))) > print('Output 3: {0}'.format(flat_it(x, list()))) > > ** Output ** > Input: [[1, 2, [3, 7]], 4] > Output 1: [1, 2, 3, 7, 4] > Output 2: [1, 2, 3, 7, 4, 1, 2, 3, 7, 4] > Output 3: [1, 2, 3, 7, 4] > > Thank you, > Bhargav. > > > On Friday, October 3, 2014 8:48 PM, Anand Chitipothu < > anandology at gmail.com> wrote: > > > > On Fri, Oct 3, 2014 at 8:26 PM, Bhargav Kowshik > wrote: > > We could use what Anand talked about at Pycon India about handling the > headers in first row of a CSV.In this scenario, instead of default for > result being None and checking if None everytime, we could have the default > value an empty list. > > def flat_it(values, result=list()): > for v in values: > if isinstance(v, list): > flat_it(v, result) > else: > result.append(v) > return result > > x = [[1, 2, [3, 4, 5, 6, 7]], 4] > print x > print flat_it(x) > > > Thats a pitfall! Try calling flat_it once again and see what you get. > Anand > > > > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com * From bhargav.kowshik at yahoo.com Fri Oct 3 18:09:31 2014 From: bhargav.kowshik at yahoo.com (Bhargav Kowshik) Date: Fri, 3 Oct 2014 16:09:31 +0000 (UTC) Subject: [BangPypers] Python List Comprehension Question In-Reply-To: References: Message-ID: <1533201105.216967.1412352571425.JavaMail.yahoo@jws10051.mail.ne1.yahoo.com> Thank you Kracekumar. http://docs.python-guide.org/en/latest/writing/gotchas/#what-you-wrote"Python?s default arguments are evaluated once when the function is defined,not each time the function is called."?Thank you, Bhargav. On Friday, October 3, 2014 9:18 PM, kracekumar ramaraju wrote: On Fri, Oct 3, 2014 at 9:04 PM, Bhargav Kowshik wrote: Nice! Thank you very much Anand.But, I still don't know what is happening.Please point me to a resource to understand what is happening. A common beginner mistake. More of such gotcha can be found here?http://docs.python-guide.org/en/latest/writing/gotchas/ . ? ** Program ** def flat_it(values, result=list()): ??? for v in values: ??????? if isinstance(v, list): ??????????? flat_it(v, result) ??????? else: ??????????? result.append(v) ??? return result x = [[1, 2, [3, 7]], 4] print('Input: {0}'.format(x)) print('Output 1: {0}'.format(flat_it(x))) print('Output 2: {0}'.format(flat_it(x))) print('Output 3: {0}'.format(flat_it(x, list()))) ** Output ** Input: [[1, 2, [3, 7]], 4] Output 1: [1, 2, 3, 7, 4] Output 2: [1, 2, 3, 7, 4, 1, 2, 3, 7, 4] Output 3: [1, 2, 3, 7, 4] Thank you, Bhargav. ? ? ?On Friday, October 3, 2014 8:48 PM, Anand Chitipothu wrote: ?On Fri, Oct 3, 2014 at 8:26 PM, Bhargav Kowshik wrote: We could use what Anand talked about at Pycon India about handling the headers in first row of a CSV.In this scenario, instead of default for result being None and checking if None everytime, we could have the default value an empty list. def flat_it(values, result=list()): ??? for v in values: ??????? if isinstance(v, list): ??????????? flat_it(v, result) ??????? else: ??????????? result.append(v) ??? return result x = [[1, 2, [3, 4, 5, 6, 7]], 4] print x print flat_it(x) Thats a pitfall! Try calling flat_it once again and see what you get. Anand _______________________________________________ BangPypers mailing list BangPypers at python.org https://mail.python.org/mailman/listinfo/bangpypers -- Thanks & Regards kracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com From rajiv.m1991 at gmail.com Sat Oct 4 13:27:50 2014 From: rajiv.m1991 at gmail.com (Rajiv Subramanian M) Date: Sat, 4 Oct 2014 16:57:50 +0530 Subject: [BangPypers] Python Gotcha Fibonacci Message-ID: Hi Group, I just went through this article http://docs.python-guide.org/en/latest/writing/gotchas/ written a Fibonacci program like this def fibonacci(next=[1], prev=[0]): data = prev.pop() prev.append(next.pop()) next.append(prev[0] + data) return data for i in range(10): print fibonacci() It actually works, it prints first 10 fibonacci numbers My question is the following code doesn't work the same way as i expected it to work. def fibonacci(next=1, prev=0): data = prev prev = next next = data + next return data for i in range(10): print fibonacci() Instead of printing Fibonacci, it just prints 10 zeros means.. does python only remembers the list in default argument? -- [image: --] Rajiv Subramanian M [image: http://]about.me/rajiv.m1991 From shankhabanerjee at gmail.com Sat Oct 4 13:35:36 2014 From: shankhabanerjee at gmail.com (shankha) Date: Sat, 4 Oct 2014 17:05:36 +0530 Subject: [BangPypers] Python Gotcha Fibonacci In-Reply-To: References: Message-ID: Try using pdb. Check the values of next and prev when it is called for the second time. Similarly check the values of next and prev in another execution. You will enjoy it :-). Try going through this answer: http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument. Thanks Shankha Banerjee On Sat, Oct 4, 2014 at 4:57 PM, Rajiv Subramanian M wrote: > Hi Group, > > I just went through this article > http://docs.python-guide.org/en/latest/writing/gotchas/ > > written a Fibonacci program like this > > def fibonacci(next=[1], prev=[0]): > data = prev.pop() > prev.append(next.pop()) > next.append(prev[0] + data) > return data > > for i in range(10): > print fibonacci() > > It actually works, it prints first 10 fibonacci numbers > > My question is the following code doesn't work the same way as i expected > it to work. > > def fibonacci(next=1, prev=0): > data = prev > prev = next > next = data + next > return data > > for i in range(10): > print fibonacci() > > Instead of printing Fibonacci, it just prints 10 zeros > > means.. does python only remembers the list in default argument? > > -- > > [image: --] > Rajiv Subramanian M > [image: http://]about.me/rajiv.m1991 > > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers From anandology at gmail.com Sun Oct 5 03:08:44 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Sun, 5 Oct 2014 06:38:44 +0530 Subject: [BangPypers] Python Gotcha Fibonacci In-Reply-To: References: Message-ID: On Sat, Oct 4, 2014 at 5:05 PM, shankha wrote: > Try using pdb. [...] Oh no! Real programmers use print. Anand From saager.mhatre at gmail.com Mon Oct 6 17:25:43 2014 From: saager.mhatre at gmail.com (Saager Mhatre) Date: Mon, 6 Oct 2014 11:25:43 -0400 Subject: [BangPypers] Python Gotcha Fibonacci In-Reply-To: References: Message-ID: Spend some time to logically think about what is semantically different in the two implementations, focus on the types of the values and operations invoked thereon. - d From shyran at gmail.com Tue Oct 7 12:23:04 2014 From: shyran at gmail.com (Kulkarni, Shreyas) Date: Tue, 7 Oct 2014 15:53:04 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 Message-ID: Hi guys, We are planning to move our production environment from 2.6 to 2.7 on one of the projects. While I understand it's not a significant upgrade, this being a production environment, I was wondering what aspects of 2.6 might break under 2.7 and what I should be watching out for. I tried searching about it, but didn't hit anything useful. Anyone here has any suggestions, or has experienced any difficulties after bumping the version to 2.7? Thanks in advance. shreyas From abdulmuneer at gmail.com Wed Oct 8 07:42:40 2014 From: abdulmuneer at gmail.com (Abdul Muneer) Date: Wed, 8 Oct 2014 11:12:40 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 In-Reply-To: References: Message-ID: Hi, As far as I know, nothing written in python should break. If you are upgrading OS too, then you should be watchful as some of the c libraries can introduce version conflicts. We had faced such a problem with pyactivemq at our office. Pyactivemq depends on activemq-cpp library which in turn depends on a few system libraries. The problem was that the development of pyactivemq stagnated while activemq-cpp moved on the version checks caused conflicts. If I used a version of activemq-cpp that satisfies pyactivemq, activemq-cpp had problems with system libraries as they too had moved on to newer versions. IIRC, I solved it by changing the regex that looks for the versions. Regards, Abdul Muneer Regards, Abdul Muneer -- Follow me on Twitter: @abdulmuneer On Tue, Oct 7, 2014 at 3:53 PM, Kulkarni, Shreyas wrote: > Hi guys, > > We are planning to move our production environment from 2.6 to 2.7 on one > of the projects. While I understand it's not a significant upgrade, this > being a production environment, I was wondering what aspects of 2.6 might > break under 2.7 and what I should be watching out for. I tried searching > about it, but didn't hit anything useful. > > Anyone here has any suggestions, or has experienced any difficulties after > bumping the version to 2.7? > > Thanks in advance. > > > shreyas > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > From awasekhirni at gmail.com Wed Oct 8 07:53:33 2014 From: awasekhirni at gmail.com (Syed Awase khirni) Date: Wed, 8 Oct 2014 11:23:33 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 In-Reply-To: References: Message-ID: hello, We are looking for exceptional programmers in Django, Python, MySQL,Postgres. freshers to 3+ years work experience. If you are recent passout, we would train you on the technologies and hire you subjected to performance. Please share your CVs regards Dr. Syed On Wed, Oct 8, 2014 at 11:12 AM, Abdul Muneer wrote: > Hi, > As far as I know, nothing written in python should break. If you are > upgrading OS too, then you should be watchful as some of the c libraries > can introduce version conflicts. > We had faced such a problem with pyactivemq at our office. Pyactivemq > depends on activemq-cpp library which in turn depends on a few system > libraries. The problem was that the development of pyactivemq stagnated > while activemq-cpp moved on the version checks caused conflicts. If I used > a version of activemq-cpp that satisfies pyactivemq, activemq-cpp had > problems with system libraries as they too had moved on to newer versions. > IIRC, I solved it by changing the regex that looks for the versions. > Regards, > Abdul Muneer > > Regards, > Abdul Muneer > > -- > Follow me on Twitter: @abdulmuneer > > On Tue, Oct 7, 2014 at 3:53 PM, Kulkarni, Shreyas > wrote: > > > Hi guys, > > > > We are planning to move our production environment from 2.6 to 2.7 on one > > of the projects. While I understand it's not a significant upgrade, this > > being a production environment, I was wondering what aspects of 2.6 might > > break under 2.7 and what I should be watching out for. I tried searching > > about it, but didn't hit anything useful. > > > > Anyone here has any suggestions, or has experienced any difficulties > after > > bumping the version to 2.7? > > > > Thanks in advance. > > > > > > shreyas > > _______________________________________________ > > BangPypers mailing list > > BangPypers at python.org > > https://mail.python.org/mailman/listinfo/bangpypers > > > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- ----------------------------------------------------------------------------------------------------------------------------------------------------- Awase Khirni Syed Ph.D (GIS, University of Zurich), M.E (BITS,Pilani). Mobile: 0091-9035433124 Tel: 0091-80-42116134 From gora at mimirtech.com Wed Oct 8 08:35:20 2014 From: gora at mimirtech.com (Gora Mohanty) Date: Wed, 8 Oct 2014 12:05:20 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 In-Reply-To: References: Message-ID: On 7 October 2014 15:53, Kulkarni, Shreyas wrote: > Hi guys, > > We are planning to move our production environment from 2.6 to 2.7 on one of the projects. While I understand it's not a significant upgrade, this being a production environment, I was wondering what aspects of 2.6 might break under 2.7 and what I should be watching out for. I tried searching about it, but didn't hit anything useful. You should take a look at https://docs.python.org/3/whatsnew/2.7.html , and as always should have test cases that should uncover any issues in the migration. One thing to watch out for is that if you have bytecode (.pyc) files, it is quite possible that they will be incompatible between 2.6 and 2.7. Regards, Gora From shyran at gmail.com Wed Oct 8 11:23:39 2014 From: shyran at gmail.com (Kulkarni, Shreyas) Date: Wed, 8 Oct 2014 14:53:39 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 In-Reply-To: References: Message-ID: Thanks Abdul. Fortunately we don't have any native bindings in the project. shreyas On Oct 8, 2014, at 11:12 AM, Abdul Muneer wrote: > Hi, > As far as I know, nothing written in python should break. If you are > upgrading OS too, then you should be watchful as some of the c libraries > can introduce version conflicts. > We had faced such a problem with pyactivemq at our office. Pyactivemq > depends on activemq-cpp library which in turn depends on a few system > libraries. The problem was that the development of pyactivemq stagnated > while activemq-cpp moved on the version checks caused conflicts. If I used > a version of activemq-cpp that satisfies pyactivemq, activemq-cpp had > problems with system libraries as they too had moved on to newer versions. > IIRC, I solved it by changing the regex that looks for the versions. > Regards, > Abdul Muneer > > Regards, > Abdul Muneer > > -- > Follow me on Twitter: @abdulmuneer > > On Tue, Oct 7, 2014 at 3:53 PM, Kulkarni, Shreyas wrote: > >> Hi guys, >> >> We are planning to move our production environment from 2.6 to 2.7 on one >> of the projects. While I understand it's not a significant upgrade, this >> being a production environment, I was wondering what aspects of 2.6 might >> break under 2.7 and what I should be watching out for. I tried searching >> about it, but didn't hit anything useful. >> >> Anyone here has any suggestions, or has experienced any difficulties after >> bumping the version to 2.7? >> >> Thanks in advance. >> >> >> shreyas >> _______________________________________________ >> BangPypers mailing list >> BangPypers at python.org >> https://mail.python.org/mailman/listinfo/bangpypers >> > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers From shyran at gmail.com Wed Oct 8 11:28:06 2014 From: shyran at gmail.com (Kulkarni, Shreyas) Date: Wed, 8 Oct 2014 14:58:06 +0530 Subject: [BangPypers] Moving from python 2.6 to 2.7 In-Reply-To: References: Message-ID: <9F76A679-F386-4BB2-B44A-C474655D3E0C@gmail.com> Thanks Gora. The test-cases are scant, at least I don't think they cover it all, and me being new to the functionality, I started looking out for inputs to avoid some deprecations across versions breaking a corner case somewhere. shreyas On Oct 8, 2014, at 12:05 PM, Gora Mohanty wrote: > On 7 October 2014 15:53, Kulkarni, Shreyas wrote: >> Hi guys, >> >> We are planning to move our production environment from 2.6 to 2.7 on one of the projects. While I understand it's not a significant upgrade, this being a production environment, I was wondering what aspects of 2.6 might break under 2.7 and what I should be watching out for. I tried searching about it, but didn't hit anything useful. > > You should take a look at https://docs.python.org/3/whatsnew/2.7.html , and as > always should have test cases that should uncover any issues in the migration. > > One thing to watch out for is that if you have bytecode (.pyc) files, > it is quite > possible that they will be incompatible between 2.6 and 2.7. > > Regards, > Gora > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers From avinashsajjan at gmail.com Wed Oct 8 12:44:46 2014 From: avinashsajjan at gmail.com (avinash sajjanshetty) Date: Wed, 8 Oct 2014 16:14:46 +0530 Subject: [BangPypers] Where to buy Python merchandise in India? Message-ID: Where can I buy Python T Shirts and mugs in India? Most of the online sites I found were from abroad and shipping/tax kills the whole deal. And also they were pretty costly. Are there any online sites in India which sell Python merch? Thanks, avi From anandology at gmail.com Wed Oct 8 12:49:06 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Wed, 8 Oct 2014 16:19:06 +0530 Subject: [BangPypers] Adding mixing at run-time Message-ID: Hi, I'm working on a slightly large application and I'm trying to model it as a some kind of plugin architecture so that it modular and I can enable or take out features without lot of code changes. One of the issues I faced was that the wanted to add some methods to a class only when a feature/plugin is enabled. Here is a simplified version of what I have: class Place(Mixable): def __init__(self, name): self.name = name def get_users(self): return "users-of-{}".format(self.name) def get_links(self): return "links-of-{}".format(self.name) There are couple of issues with this. 1. The logic for computing users or links doesn't really belong to this file. I wanted to that in a separate module for modularity. 2. The Place class will become too large to manage over time. So, I came up with the following approach to address these issues. # place.py class Mixable(object): """Magic class to allow adding mixins to the class at run-time. """ @classmethod def mixin(cls, mixin): """Decorator to add a mixin to the class runtime. """ cls.__bases__ = cls.__bases__ + (mixin,) class Place(Mixable): def __init__(self, name): self.name = name # users.py @Place.mixin class UsersMixin(object): def get_users(self): return "users-of-{}".format(self.name) # links.py @Place.mixin class LinksMixin(object): def get_links(self): return "links-of-{}".format(self.name) p = Place('bangalore') print(p.get_users()) print(p.get_links()) With this I was able to split the class into 3 files and now I have flexibility of deciding which features enable from a config file. What do you guys think of this approach? Is this a good practice? Are there any know flaws in this approach? How did you solve that issue when you faced similar situation? Anand From kracethekingmaker at gmail.com Thu Oct 9 08:00:37 2014 From: kracethekingmaker at gmail.com (kracekumar ramaraju) Date: Thu, 9 Oct 2014 11:30:37 +0530 Subject: [BangPypers] Adding mixing at run-time In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 4:19 PM, Anand Chitipothu wrote: > Hi, > > I'm working on a slightly large application and I'm trying to model it as a > some kind of plugin architecture so that it modular and I can enable or > take out features without lot of code changes. > > One of the issues I faced was that the wanted to add some methods to a > class only when a feature/plugin is enabled. > > Here is a simplified version of what I have: > > class Place(Mixable): > def __init__(self, name): > self.name = name > > def get_users(self): > return "users-of-{}".format(self.name) > > def get_links(self): > return "links-of-{}".format(self.name) > > There are couple of issues with this. > > 1. The logic for computing users or links doesn't really belong to this > file. I wanted to that in a separate module for modularity. > > 2. The Place class will become too large to manage over time. > > So, I came up with the following approach to address these issues. > > # place.py > > class Mixable(object): > """Magic class to allow adding mixins to the class at run-time. > """ > @classmethod > def mixin(cls, mixin): > """Decorator to add a mixin to the class runtime. > """ > cls.__bases__ = cls.__bases__ + (mixin,) > > class Place(Mixable): > def __init__(self, name): > self.name = name > > # users.py > @Place.mixin > class UsersMixin(object): > def get_users(self): > return "users-of-{}".format(self.name) > > Is there any specific reason for using decorators ? > # links.py > @Place.mixin > class LinksMixin(object): > def get_links(self): > return "links-of-{}".format(self.name) > > p = Place('bangalore') > print(p.get_users()) > print(p.get_links()) > > I somehow feel this can lead to unexpected behaviour since Mixable classes are added at various files. This pattern looks like global variable argument (global variables are bad). Say if Idecorate Foo with @Place.mixin by mistake, behaviour of the Foo will be available in Place class and leads to side effect. How about #dispatcher.py # import all the classes def get_place_class(): # Check for features for cls in classes: Place.__bases__ = Place.__bases__ + (cls,) return Place > With this I was able to split the class into 3 files and now I have > flexibility of deciding which features enable from a config file. > > What do you guys think of this approach? > My only concern base classes are added in different files and difficult to remember. Is this a good practice? > Are there any know flaws in this approach? How did you solve that issue when you faced similar situation? > > Did I understand the problem correctly ? > Anand > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com * From superpulse.x at gmail.com Thu Oct 9 09:51:15 2014 From: superpulse.x at gmail.com (venkatakrishnan g) Date: Thu, 9 Oct 2014 13:21:15 +0530 Subject: [BangPypers] Adding mixing at run-time In-Reply-To: References: Message-ID: I think this is a very nice approach. I disagree that that you could decorate a class as @Place.mixin by mistake, In fact i think the decorator actually makes it absolutely clear its purpose. However, the Place.mixin should return the mixin class. @classmethod def mixin(cls, mixin): """Decorator to add a mixin to the class runtime. """ cls.__bases__ = cls.__bases__ + (mixin,) return mixin This: 1. Allows the class to be mixed-in into other classes if there's need for it 2. Class decorators should return classes, else LinksMixin evaluates to None On 9 October 2014 11:30, kracekumar ramaraju wrote: > On Wed, Oct 8, 2014 at 4:19 PM, Anand Chitipothu > wrote: > > > Hi, > > > > I'm working on a slightly large application and I'm trying to model it > as a > > some kind of plugin architecture so that it modular and I can enable or > > take out features without lot of code changes. > > > > One of the issues I faced was that the wanted to add some methods to a > > class only when a feature/plugin is enabled. > > > > Here is a simplified version of what I have: > > > > class Place(Mixable): > > def __init__(self, name): > > self.name = name > > > > def get_users(self): > > return "users-of-{}".format(self.name) > > > > def get_links(self): > > return "links-of-{}".format(self.name) > > > > There are couple of issues with this. > > > > 1. The logic for computing users or links doesn't really belong to this > > file. I wanted to that in a separate module for modularity. > > > > 2. The Place class will become too large to manage over time. > > > > So, I came up with the following approach to address these issues. > > > > # place.py > > > > class Mixable(object): > > """Magic class to allow adding mixins to the class at run-time. > > """ > > @classmethod > > def mixin(cls, mixin): > > """Decorator to add a mixin to the class runtime. > > """ > > cls.__bases__ = cls.__bases__ + (mixin,) > > > > class Place(Mixable): > > def __init__(self, name): > > self.name = name > > > > # users.py > > @Place.mixin > > class UsersMixin(object): > > def get_users(self): > > return "users-of-{}".format(self.name) > > > > > Is there any specific reason for using decorators ? > > > > > # links.py > > @Place.mixin > > class LinksMixin(object): > > def get_links(self): > > return "links-of-{}".format(self.name) > > > > p = Place('bangalore') > > print(p.get_users()) > > print(p.get_links()) > > > > > > I somehow feel this can lead to unexpected behaviour since Mixable classes > are added at various files. > This pattern looks like global variable argument (global variables are > bad). Say if Idecorate Foo with @Place.mixin by mistake, behaviour of the > Foo will be available in Place class and leads to side effect. > > How about > > #dispatcher.py > # import all the classes > > def get_place_class(): > # Check for features > for cls in classes: > Place.__bases__ = Place.__bases__ + (cls,) > return Place > > > > > With this I was able to split the class into 3 files and now I have > > flexibility of deciding which features enable from a config file. > > > > What do you guys think of this approach? > > > > My only concern base classes are added in different files and difficult to > remember. > > Is this a good practice? > > Are there any know flaws in this approach? > > How did you solve that issue when you faced similar situation? > > > > > Did I understand the problem correctly ? > > > > Anand > > _______________________________________________ > > BangPypers mailing list > > BangPypers at python.org > > https://mail.python.org/mailman/listinfo/bangpypers > > > > > > -- > > *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus > Torvaldshttp://kracekumar.com * > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > From deepu.dtp at gmail.com Thu Oct 9 12:56:25 2014 From: deepu.dtp at gmail.com (Deepu Thomas Philip) Date: Thu, 9 Oct 2014 16:26:25 +0530 Subject: [BangPypers] Adding mixing at run-time In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 4:19 PM, Anand Chitipothu wrote: > Hi, > > I'm working on a slightly large application and I'm trying to model it as a > some kind of plugin architecture so that it modular and I can enable or > take out features without lot of code changes. > > One of the issues I faced was that the wanted to add some methods to a > class only when a feature/plugin is enabled. > > Here is a simplified version of what I have: > > class Place(Mixable): > def __init__(self, name): > self.name = name > > def get_users(self): > return "users-of-{}".format(self.name) > > def get_links(self): > return "links-of-{}".format(self.name) > > There are couple of issues with this. > > 1. The logic for computing users or links doesn't really belong to this > file. I wanted to that in a separate module for modularity. > > 2. The Place class will become too large to manage over time. > > So, I came up with the following approach to address these issues. > > # place.py > > class Mixable(object): > """Magic class to allow adding mixins to the class at run-time. > """ > @classmethod > def mixin(cls, mixin): > """Decorator to add a mixin to the class runtime. > """ > cls.__bases__ = cls.__bases__ + (mixin,) > > class Place(Mixable): > def __init__(self, name): > self.name = name > > # users.py > @Place.mixin > class UsersMixin(object): > def get_users(self): > return "users-of-{}".format(self.name) > > # links.py > @Place.mixin > class LinksMixin(object): > def get_links(self): > return "links-of-{}".format(self.name) > p = Place('bangalore') > print(p.get_users()) > print(p.get_links()) > > With this I was able to split the class into 3 files and now I have > flexibility of deciding which features enable from a config file. > > While trying to remove logic that does not belong in the place module, you introduced *place* into two other modules where it does not belong. I did not understand the approach completely. >From a config file how does one achieve plugin like architecture? What do you guys think of this approach? > Is this a good practice? > Are there any know flaws in this approach? > Not sure if this is a flaw or expected behaviour I could not get a Place + UserMixin instance and a Place + LinksMixin instance to coexist in the same scope at the same time. Importing any of the mixins led to pollution of existing Place instances. from place import Place p = Place("bangalore") from user import UserMixin print p.get_links() # outputs 'links-of-bangalore' > How did you solve that issue when you faced similar situation? Any reason to not use a builder pattern or a factory method pattern? > > Anand > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > From anandology at gmail.com Thu Oct 9 13:44:30 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Thu, 9 Oct 2014 17:14:30 +0530 Subject: [BangPypers] Adding mixing at run-time In-Reply-To: References: Message-ID: On Thu, Oct 9, 2014 at 11:30 AM, kracekumar ramaraju < kracethekingmaker at gmail.com> wrote: > On Wed, Oct 8, 2014 at 4:19 PM, Anand Chitipothu > wrote: > > > Hi, > > > > I'm working on a slightly large application and I'm trying to model it > as a > > some kind of plugin architecture so that it modular and I can enable or > > take out features without lot of code changes. > > > > One of the issues I faced was that the wanted to add some methods to a > > class only when a feature/plugin is enabled. > > > > Here is a simplified version of what I have: > > > > class Place(Mixable): > > def __init__(self, name): > > self.name = name > > > > def get_users(self): > > return "users-of-{}".format(self.name) > > > > def get_links(self): > > return "links-of-{}".format(self.name) > > > > There are couple of issues with this. > > > > 1. The logic for computing users or links doesn't really belong to this > > file. I wanted to that in a separate module for modularity. > > > > 2. The Place class will become too large to manage over time. > > > > So, I came up with the following approach to address these issues. > > > > # place.py > > > > class Mixable(object): > > """Magic class to allow adding mixins to the class at run-time. > > """ > > @classmethod > > def mixin(cls, mixin): > > """Decorator to add a mixin to the class runtime. > > """ > > cls.__bases__ = cls.__bases__ + (mixin,) > > > > class Place(Mixable): > > def __init__(self, name): > > self.name = name > > > > # users.py > > @Place.mixin > > class UsersMixin(object): > > def get_users(self): > > return "users-of-{}".format(self.name) > > > > > Is there any specific reason for using decorators ? > Just because I felt that provides a nice API. I would have used a more explicit approach like the following, but I liked the decorators one better. def setup_plugin(): register_place_plugin(UsersMixin) > # links.py > > @Place.mixin > > class LinksMixin(object): > > def get_links(self): > > return "links-of-{}".format(self.name) > > > > p = Place('bangalore') > > print(p.get_users()) > > print(p.get_links()) > > > I somehow feel this can lead to unexpected behaviour since Mixable classes > are added at various files. > Yes, it requires some discipline. > This pattern looks like global variable argument (global variables are > bad). Say if Idecorate Foo with @Place.mixin by mistake, behaviour of the > Foo will be available in Place class and leads to side effect. > Well that is a compromise. Same as Flask vs. Django URL routing. > > How about > > #dispatcher.py > # import all the classes > > def get_place_class(): > # Check for features > for cls in classes: > Place.__bases__ = Place.__bases__ + (cls,) > return Place > That should be setup_place_class() and that should be called only once. But the decorators approach makes calling it twice impossible. > > With this I was able to split the class into 3 files and now I have > > flexibility of deciding which features enable from a config file. > > > > What do you guys think of this approach? > > > > My only concern base classes are added in different files and difficult to > remember. > Yes, it will become difficult if not used with care, but I think it can be used very elegantly if enough care is given. What I really want is multiple people work on separate parts of the system without having to touch the core code. > Is this a good practice? > > Are there any know flaws in this approach? > > How did you solve that issue when you faced similar situation? > > > > > Did I understand the problem correctly ? > I think so. Anand From rajalokan at gmail.com Fri Oct 10 10:36:56 2014 From: rajalokan at gmail.com (Okan bhan) Date: Fri, 10 Oct 2014 14:06:56 +0530 Subject: [BangPypers] Asynchronous method calls in python Message-ID: Hi, I'm working on an appengine + flask application which makes multiple requests to third party APIs as part of one request. All of these are independent. So I was hoping what should be the best way to make these method calls asynchronously. Whatever I know: * *Using multi-threading in python*: I've heard not to try multithreaded in your application itself it you are not sure. Rather rely on application server. * *Using something like Twisted*: Not an options as my stack doesn't allow it. Please suggest me what should be the best solution here? Alok From anandology at gmail.com Fri Oct 10 10:50:00 2014 From: anandology at gmail.com (Anand Chitipothu) Date: Fri, 10 Oct 2014 14:20:00 +0530 Subject: [BangPypers] Asynchronous method calls in python In-Reply-To: References: Message-ID: On Fri, Oct 10, 2014 at 2:06 PM, Okan bhan wrote: > Hi, > > I'm working on an appengine + flask application which makes multiple > requests to third party APIs as part of one request. All of these are > independent. > > So I was hoping what should be the best way to make these method calls > asynchronously. Whatever I know: > > * *Using multi-threading in python*: I've heard not to try multithreaded in > your application itself it you are not sure. Rather rely on application > server. > * *Using something like Twisted*: Not an options as my stack doesn't allow > it. > > Please suggest me what should be the best solution here? > Have you looked at app engine API for making async fetch requests? https://cloud.google.com/appengine/docs/python/urlfetch/asynchronousrequests Anand From shyran at gmail.com Fri Oct 10 10:43:53 2014 From: shyran at gmail.com (Kulkarni, Shreyas) Date: Fri, 10 Oct 2014 14:13:53 +0530 Subject: [BangPypers] [JOBS] Looking for python/bash profiles Message-ID: Hi guys, We are looking for strong python and bash profiles in my team in Akamai Technologies. Here are a few criteria - Good educational and professional background Strong python design/development experience (this is not web-dev kind of a profile though) with good coding standards Should be comfortable and at home in Linux. Good hands on bash/shell-scripting experience will be a big plus. Good grasp of CS fundamentals like data structures, algorithms, networking is necessary. Knowledge of OOAD/OOP concepts will be a big plus. Good communication skills It's a full time requirement, based out of Bangalore. Consultants please excuse. If anyone is interested, write to me with your profile. Please *DO NOT* reply-to-all. Thanks, Shreyas Kulkarni From vikramuk at gmail.com Sat Oct 11 18:53:36 2014 From: vikramuk at gmail.com (Vikram Upadhya) Date: Sat, 11 Oct 2014 22:23:36 +0530 Subject: [BangPypers] [JOBS] Looking for python/bash profiles In-Reply-To: References: Message-ID: Hi Shreyas, Could you help conect me to Jobs with about 4 Years experience on Scripting Languages. With regards, Vikram U 9916028682 On Fri, Oct 10, 2014 at 2:13 PM, Kulkarni, Shreyas wrote: > Hi guys, > > We are looking for strong python and bash profiles in my team in Akamai > Technologies. Here are a few criteria - > > Good educational and professional background > Strong python design/development experience (this is not web-dev kind of a > profile though) with good coding standards > Should be comfortable and at home in Linux. Good hands on > bash/shell-scripting experience will be a big plus. > Good grasp of CS fundamentals like data structures, algorithms, networking > is necessary. > Knowledge of OOAD/OOP concepts will be a big plus. > Good communication skills > > It's a full time requirement, based out of Bangalore. Consultants please > excuse. > > If anyone is interested, write to me with your profile. Please *DO NOT* > reply-to-all. > > Thanks, > Shreyas Kulkarni > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- -Vikram From jyothi.nadu at gmail.com Mon Oct 13 06:43:46 2014 From: jyothi.nadu at gmail.com (Jyothi Naidu) Date: Mon, 13 Oct 2014 10:13:46 +0530 Subject: [BangPypers] [JOBS] Looking for python/bash profiles In-Reply-To: References: Message-ID: Yes there are many more jobs available for 4 Years on PYTHON DEVELOPER On Sat, Oct 11, 2014 at 10:23 PM, Vikram Upadhya wrote: > Hi Shreyas, > Could you help conect me to Jobs with about 4 Years experience on > Scripting Languages. > > > With regards, > Vikram U > 9916028682 > > On Fri, Oct 10, 2014 at 2:13 PM, Kulkarni, Shreyas > wrote: > > > Hi guys, > > > > We are looking for strong python and bash profiles in my team in Akamai > > Technologies. Here are a few criteria - > > > > Good educational and professional background > > Strong python design/development experience (this is not web-dev kind of > a > > profile though) with good coding standards > > Should be comfortable and at home in Linux. Good hands on > > bash/shell-scripting experience will be a big plus. > > Good grasp of CS fundamentals like data structures, algorithms, > networking > > is necessary. > > Knowledge of OOAD/OOP concepts will be a big plus. > > Good communication skills > > > > It's a full time requirement, based out of Bangalore. Consultants please > > excuse. > > > > If anyone is interested, write to me with your profile. Please *DO NOT* > > reply-to-all. > > > > Thanks, > > Shreyas Kulkarni > > _______________________________________________ > > BangPypers mailing list > > BangPypers at python.org > > https://mail.python.org/mailman/listinfo/bangpypers > > > > > > -- > -Vikram > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- Regards, Jyothi Naidu +91 8123459658 From er.kalra80 at gmail.com Tue Oct 14 12:16:39 2014 From: er.kalra80 at gmail.com (neeraj kalra) Date: Tue, 14 Oct 2014 15:46:39 +0530 Subject: [BangPypers] any guidance would be appreicated Message-ID: Sorry sending this mail without knowing all memebsr..I need assistance from you and would appreciate if you provide any guidance to solve my issues. 1. I am working on *customized mail client desktop app* to cater for windows based at stage one and linux at a later stage. 2. firstly i am not able to create a installer for windows... i used CX_Freeze etc.. still there is no success to me ...Kindly suggest how to create a installer for windows. My app has *many py* scripts and is also using lot of dependencies dll.. and is based on tkinter etc 4. Is it possible for me import address books of yahoo and gmail of the user who enters his username and password (using python Tkinter) ?? Your help will be appreciated. thnx n regards kalra From kausikram at gmail.com Tue Oct 14 13:53:10 2014 From: kausikram at gmail.com (kausikram krishnasayee) Date: Tue, 14 Oct 2014 17:23:10 +0530 Subject: [BangPypers] [Job] OrangeScape is Looking for Passionate Pythonistas Message-ID: Hi, We at OrangeScape are hiring Python Developers who would join our team in building some amazing cloud based products. OrangeScape was founded in 2003 and is one among the Global 10 companies featured by Forrester and Gartner in the Platform-as-a-service Category. We are a bunch of dynamic geeks who work with cutting edge technology in the cloud space. The details of about the opening are available at: http://grow.orangescape.com?utm_medium=email If you are a passionate python developer and enjoy working with a team of equally talented code geeks then you should totally apply. Do check it out! And yes, we are known for taking good care of our employees :) cheers, Kausikram From ppc.lists at gmail.com Thu Oct 16 08:25:26 2014 From: ppc.lists at gmail.com (Pradip Caulagi) Date: Thu, 16 Oct 2014 11:55:26 +0530 Subject: [BangPypers] Asynchronous method calls in python In-Reply-To: References: Message-ID: <543F64D6.8090704@gmail.com> On Friday 10 October 2014 02:06 PM, Okan bhan wrote: > Hi, > > I'm working on an appengine + flask application which makes multiple > requests to third party APIs as part of one request. All of these are > independent. > > So I was hoping what should be the best way to make these method calls > asynchronously. Whatever I know: You could also use - https://docs.python.org/3/library/concurrent.futures.html. It is ported to Python 2 in https://pypi.python.org/pypi/futures. I tried concurrent.futures a bit - https://medium.com/@caulagi/python-concurrent-futures-1028b47db1cf -- Pradip P Caulagi From swvist at gmail.com Thu Oct 16 08:39:41 2014 From: swvist at gmail.com (Vipin Nair) Date: Thu, 16 Oct 2014 12:09:41 +0530 Subject: [BangPypers] Asynchronous method calls in python In-Reply-To: References: Message-ID: > I'm working on an appengine + flask application which makes multiple > requests to third party APIs as part of one request. All of these are > independent. > > So I was hoping what should be the best way to make these method calls > asynchronously. Whatever I know: I have used grequests[1] in the past to do something similar. [1]: https://github.com/kennethreitz/grequests -- Regards, Vipin From rajalokan at gmail.com Thu Oct 16 14:50:29 2014 From: rajalokan at gmail.com (Okan bhan) Date: Thu, 16 Oct 2014 18:20:29 +0530 Subject: [BangPypers] Asynchronous method calls in python Message-ID: > > Thanks everyone for answers. I'm looking into these options. Thanks again. > Regards Alok From tk446 at snu.edu.in Wed Oct 22 13:41:19 2014 From: tk446 at snu.edu.in (Tarun Kumar) Date: Wed, 22 Oct 2014 17:11:19 +0530 Subject: [BangPypers] Micropython without pyboard Message-ID: Hello all Greetings of diwali..!! I want to use micropython without pyboard. Instead of pyboard I am using " stm32f4" which is very similar to pyboard, the only difference is pyboard is pre-installed with micropython. And I want to install it on stm32f4 board. I have source code of micropython. But what package is required to port it on hardware. -- -Tarun Kumar Shiv Nadar University ---------------------------------------- From joepaulp at gmail.com Thu Oct 23 08:55:56 2014 From: joepaulp at gmail.com (Joe Paul) Date: Thu, 23 Oct 2014 08:55:56 +0200 Subject: [BangPypers] From: Joe Paul Message-ID: Hiya bangpypers http://mylaughablenews.com/mouth.php?death=3egb5s0hf6bbvpcvkdkd joepaulp at gmail.com From rajalokan at gmail.com Sun Oct 26 06:21:00 2014 From: rajalokan at gmail.com (Okan bhan) Date: Sun, 26 Oct 2014 10:51:00 +0530 Subject: [BangPypers] Evaluating a string against mapping in python. Message-ID: Hello everyone, Hope you all celebrated festival of Diwali with your loved ones. Wishes from my side to each one of you. I'm facing issue in understanding python's 'eval' function's behaviour. I've no previous deep knowledge of using 'eval' except that "it is used to evaluate a string just like on python prompt". While working on a feature on pytest, I encountered usage of eval against a map. For a very simple case, I wanted to check if a string exists within a list. Very simple >>> 'foo' in list_foo. But string 'foo' can contain expression (like 'foo and bar'). To check this, I see they have used something like >>> eval('foo and bar', {}, mapping). A simple implementation of this is: class SimpleMapping: def __init__(self, items): self._items = items def __getitems__(self, subitem): print('*' * 20) for item in self._items: if subitem in item: return True return False Playing around against it for a bit. >>> mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc'])) >>> eval('ppp', {}, mapping) ******************** False >>> eval('aa', {}, mapping) ******************** True >>> eval('xxx and aaa', {}, mapping) ******************** False >>> eval('xxx or aaa', {}, mapping) ******************** ******************** True Struggled in beginning but now they all seem obvious to me. Tricky is: >>> eval('5.6', {}, mapping) 5.6 >>> eval('aa.a', {}, mapping) AttributeError: 'bool' object has no attribute 'a' My doubts are: a. Why it didn't run for numeric 5.6? Also why is dot separated '5.6' any different to 'aa.a'? I looked around on eval documentation and examples but couldn't find use of eval with a mapping. b. I see many blogs suggesting to refrain from using eval unless absolutely needed. Is this one use case we must use it? Do we have any better way to evaluate this? c. If indeed, I have to evaluate a string containing dots, how to do in the above scenario? Would appreciate any pointers or more clarity on this. Thanks & Regards Alok From noufal at nibrahim.net.in Sun Oct 26 12:58:31 2014 From: noufal at nibrahim.net.in (Noufal Ibrahim KV) Date: Sun, 26 Oct 2014 17:28:31 +0530 Subject: [BangPypers] Evaluating a string against mapping in python. In-Reply-To: (Okan bhan's message of "Sun, 26 Oct 2014 10:51:00 +0530") References: Message-ID: <87k33njb4o.fsf@nibrahim.net.in> On Sun, Oct 26 2014, Okan bhan wrote: [...] > A simple implementation of this is: > > class SimpleMapping: > def __init__(self, items): > self._items = items > > def __getitems__(self, subitem): > print('*' * 20) > for item in self._items: > if subitem in item: > return True > return False This is broken in two ways 1. The magic method is __getitem__ (not __getitems__). I'm assuming it's a typo otherwise, the rest of your code will not work even as you've mentioned. 2. A mapping object is similar to a dictionary. It should return the actual object if you try to access it. Not a boolean True or False. The mapping objects given are specifications of the locals and globals in which you will evaluate your string. Consult help("eval") for more information. eval(source[, globals[, locals]]) -> value > Playing around against it for a bit. >>>> mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc'])) >>>> eval('ppp', {}, mapping) > ******************** > False >>>> eval('aa', {}, mapping) > ******************** > True >>>> eval('xxx and aaa', {}, mapping) > ******************** > False >>>> eval('xxx or aaa', {}, mapping) > ******************** > ******************** > True > > Struggled in beginning but now they all seem obvious to me. Tricky is: Look at my comment above. Your Mapping object is flawed and all these responses are quite wrong. > >>>> eval('5.6', {}, mapping) > 5.6 I'm not sure how this will work. In my case, I see this. >>> mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc'])) >>> eval('5.6', {}, mapping) Traceback (most recent call last): File "", line 1, in TypeError: locals must be a mapping >>> >>>> eval('aa.a', {}, mapping) > AttributeError: 'bool' object has no attribute 'a' > > My doubts are: > a. Why it didn't run for numeric 5.6? Also why is dot separated '5.6' any > different to 'aa.a'? I looked around on eval documentation and examples but > couldn't find use of eval with a mapping. 5.6 is not an attribute access. 5.6 is is a floating point number. aa.a is an attribute access. It will first return False for `aa` since there is no such key and your code returns False and then try to access `a` in the Boolean which, predictably, fails. > b. I see many blogs suggesting to refrain from using eval unless > absolutely needed. Is this one use case we must use it? Do we have any > better way to evaluate this? I'm not sure what exactly you want to do. Can you explain again? > c. If indeed, I have to evaluate a string containing dots, how to do > in the above scenario? The object whose attribute you're trying to access should be there in the locals or globals and then should have an attribute with the given name. It will work then. [...] -- Cordially, Noufal http://nibrahim.net.in From murali.malladi at gmail.com Mon Oct 27 12:52:40 2014 From: murali.malladi at gmail.com (Murali Krishna) Date: Mon, 27 Oct 2014 17:22:40 +0530 Subject: [BangPypers] [JOBS] - Opportunity in Test Framework Development & Test Automation team at Nutanix Bangalore Message-ID: Hi All, We have multiple positions open for highly skilled Python Programmers (of-course with relevant background), for our new team at Nutanix, Bangalore (http://www.nutanix.com) Please note that the team is being setup newly, so our humble request to engineers is to apply only if they consider their level in Python and Test frameworks development to be "Intermediate to Expert". Job Description: https://hire.jobvite.com/j?cj=oaBAZfw4&s=Personal_Message Apply Online: https://hire.jobvite.com/j?aj=oaBAZfw4&s=Personal_Message Note that the Lead position is already closed. All open positions are Individual Contributor roles and experience range between 3-10 years. Thanks, Murali Malladi https://in.linkedin.com/in/muralimalladi From rajalokan at gmail.com Mon Oct 27 16:47:28 2014 From: rajalokan at gmail.com (Okan bhan) Date: Mon, 27 Oct 2014 21:17:28 +0530 Subject: [BangPypers] BangPypers Digest, Vol 86, Issue 16 In-Reply-To: References: Message-ID: Hi Noufal, Thanks for responding and helping me explaining these. I see lots of my doubts are clear, except last (c). My explanations are inline. > A simple implementation of this is: > > > > class SimpleMapping: > > def __init__(self, items): > > self._items = items > > > > def __getitems__(self, subitem): > > print('*' * 20) > > for item in self._items: > > if subitem in item: > > return True > > return False > > This is broken in two ways > 1. The magic method is __getitem__ (not __getitems__). I'm assuming it's > a typo otherwise, the rest of your code will not work even as you've > mentioned. > Yes. Indeed it should be __getitem__. It was typo while manually typing in gmail. > 2. A mapping object is similar to a dictionary. It should > return the actual object if you try to access it. Not a boolean True > or False. > Agree with you. Ideally it should have returned object and I can test by `if obj` or `if not obj`. Lets assume for now I want to continue with this. > > The mapping objects given are specifications of the locals and globals > in which you will evaluate your string. Consult help("eval") for more > information. > > eval(source[, globals[, locals]]) -> value > Makes sense. So essentially I'm trying to evaluate and expression ('foo' or 'foo and bar') against a local mapping. Not fully confident but I can see the use of locals & globals here. > Look at my comment above. Your Mapping object is flawed and all these > responses are quite wrong. > Yes. Sorry for the typo. Without typo these will be the expected answers. > > > > >>>> eval('5.6', {}, mapping) > > 5.6 > > I'm not sure how this will work. In my case, I see this. > > >>> mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc'])) > >>> eval('5.6', {}, mapping) > Traceback (most recent call last): > File "", line 1, in > TypeError: locals must be a mapping > >>> > > That is strange, I'm still getting 5.6 as result. I tried on different python versions as well. > > >>>> eval('aa.a', {}, mapping) > > AttributeError: 'bool' object has no attribute 'a' > > > > > My doubts are: > > a. Why it didn't run for numeric 5.6? Also why is dot separated '5.6' any > > different to 'aa.a'? I looked around on eval documentation and examples > but > > couldn't find use of eval with a mapping. > > 5.6 is not an attribute access. 5.6 is is a floating point number. aa.a > is an attribute access. It will first return False for `aa` since there > is no such key and your code returns False and then try to access `a` in > the Boolean which, predictably, fails. > > Big thanks for this. Let me explain what, I understood here. Lets say statement we want to evaluate is `eval(expression)`. Python starts checking 'expression' against each datatype starting from int -> float -> str. For all native datatypes, it will return corresponding result. Finally if it doesn't matches any of native types, tries to access against mapping(or any other object in local or global scope). Which is the reason, >> type(eval('5.6')) is float >> type(eval("'5.6'") is str (expression is under double quotes). For the case of eval('aa.a'), it first tries to match 'aa'. This is not any native type so goes to check in mapping and finds it True. Then tries to find attribute 'a' of returned type (a boolean). Hence boolean object has no attribute 'a'. > > b. I see many blogs suggesting to refrain from using eval unless > > absolutely needed. Is this one use case we must use it? Do we have any > > better way to evaluate this? > > I'm not sure what exactly you want to do. Can you explain again? > I came across blog posts suggesting not to use eval mostly as it can lead to un-secure code. So wanted to check should I put efforts in solving this with 'eval' or not. Not an option now. I will explain my problem in next question. > > > c. If indeed, I have to evaluate a string containing dots, how to do > > in the above scenario? > > The object whose attribute you're trying to access should be there in > the locals or globals and then should have an attribute with the given > name. It will work then. > [...] > yes. If my above observation is correct, this is clear to me. I will try to explain my problem: I have a list of strings ( say ['aaa', 'bbb', '4.5-'] ) and I want to check if an expression (say 'aa') is a substring of any of this item. Simply: all([ item for item in ['aaa', 'bbb', '4.5-'] if 'aa' in item]) ==> gives True as 'aa' is a substring of 'aaa'. But my expression can be a logical expression like 'aa or bb', 'aa and bbb', 'aaa and 4.5' etc. This works in my above implementation. If we assume mapping object from above. Writing it again here for ease. > class SimpleMapping: > def __init__(self, items): > self._items = items > > def __getitem__(self, subitem): > for item in self._items: > if subitem in item: > return True > return False >>> mapping = SimpleMapping(set(['aaa', 'bbb', '4.5-'])) >>> eval('aa and bb', {}, mapping) True # since both are substring >>> eval('aa and bbb', {}, mapping) True # again since both are substring >>> eval('aa and bbbb', {}, mapping) False # 'bbbb' fails. So till now it works fine for my case. But in case if I want to check for '4.5' in this. >>> eval('aaaa or bbbb or 4.5') 4.5 # Fails for 'aaaa', fails for 'bbbb' but evaluates '4.5' as 4.5. Something I don't want. It should be checking 4.5 against mapping and I want a boolean True here. If I am unclear, I will repeat my problem again. Problem: How can I evaluate a logical expression, in python where expression contains a dot ('.'). Analysis: First thing strike in my mind is to use eval but that fails on expression with a dot. My tries are: *Try A:* I was thinking something like, transform '.' to '#' (or anything else). For eg. 'aaaa or bbbb or 4.5' becomes 'aaaa or bbbb or 4#5'. Now if eval('4#5') goes to check inside our mapping we are good. We can transform back and evaluate. But sadly eval('4#5') gives 4. Tried with many characters, any hits here? *Try B:* Other option is extracting operators out of string ( by list comprehension or using regular expression) and operator on these string components. Is there any direct way to get logical operators from string. I found (c for c in s if c in '+-/*()_') to get mathematical operators. I will try this option tonight. Sorry for long reply and redundant answer but I wanted to be clear. If I was able to explain properly can you suggest anything here? Thanks & Regard Alok From noufal at nibrahim.net.in Mon Oct 27 16:58:58 2014 From: noufal at nibrahim.net.in (Noufal Ibrahim KV) Date: Mon, 27 Oct 2014 21:28:58 +0530 Subject: [BangPypers] BangPypers Digest, Vol 86, Issue 16 In-Reply-To: (Okan bhan's message of "Mon, 27 Oct 2014 21:17:28 +0530") References: Message-ID: <877fzlfqrh.fsf@nibrahim.net.in> On Mon, Oct 27 2014, Okan bhan wrote: > Hi Noufal, > > Thanks for responding and helping me explaining these. I see lots of my > doubts are clear, except last (c). My explanations are inline. > >> A simple implementation of this is: >> > >> > class SimpleMapping: >> > def __init__(self, items): >> > self._items = items >> > >> > def __getitems__(self, subitem): >> > print('*' * 20) >> > for item in self._items: >> > if subitem in item: >> > return True >> > return False >> >> This is broken in two ways >> 1. The magic method is __getitem__ (not __getitems__). I'm assuming it's >> a typo otherwise, the rest of your code will not work even as you've >> mentioned. >> > Yes. Indeed it should be __getitem__. It was typo while manually typing in > gmail. > > >> 2. A mapping object is similar to a dictionary. It should >> return the actual object if you try to access it. Not a boolean True >> or False. >> > Agree with you. Ideally it should have returned object and I can test by > `if obj` or `if not obj`. Lets assume for now I want to continue with this. > >> >> The mapping objects given are specifications of the locals and globals >> in which you will evaluate your string. Consult help("eval") for more >> information. >> >> eval(source[, globals[, locals]]) -> value >> > Makes sense. So essentially I'm trying to evaluate and expression ('foo' or > 'foo and bar') against a local mapping. Not fully confident but I can see > the use of locals & globals here. > > >> Look at my comment above. Your Mapping object is flawed and all these >> responses are quite wrong. >> > > Yes. Sorry for the typo. Without typo these will be the expected answers. > >> >> > >> >>>> eval('5.6', {}, mapping) >> > 5.6 >> >> I'm not sure how this will work. In my case, I see this. >> >> >>> mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc'])) >> >>> eval('5.6', {}, mapping) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: locals must be a mapping >> >>> >> >> That is strange, I'm still getting 5.6 as result. I tried on different > python versions as well. > >> >> >>>> eval('aa.a', {}, mapping) >> > AttributeError: 'bool' object has no attribute 'a' >> > >> >> > My doubts are: >> > a. Why it didn't run for numeric 5.6? Also why is dot separated '5.6' any >> > different to 'aa.a'? I looked around on eval documentation and examples >> but >> > couldn't find use of eval with a mapping. >> >> 5.6 is not an attribute access. 5.6 is is a floating point number. aa.a >> is an attribute access. It will first return False for `aa` since there >> is no such key and your code returns False and then try to access `a` in >> the Boolean which, predictably, fails. >> >> Big thanks for this. Let me explain what, I understood here. > Lets say statement we want to evaluate is `eval(expression)`. Python starts > checking 'expression' against each datatype starting from int -> float -> > str. For all native datatypes, it will return corresponding result. Finally > if it doesn't matches any of native types, tries to access against > mapping(or any other object in local or global scope). > > Which is the reason, >>> type(eval('5.6')) is float >>> type(eval("'5.6'") is str (expression is under double quotes). > > For the case of eval('aa.a'), it first tries to match 'aa'. This is not any > native type so goes to check in mapping and finds it True. Then tries to > find attribute 'a' of returned type (a boolean). Hence boolean object has > no attribute 'a'. > > >> > b. I see many blogs suggesting to refrain from using eval unless >> > absolutely needed. Is this one use case we must use it? Do we have any >> > better way to evaluate this? >> >> I'm not sure what exactly you want to do. Can you explain again? >> > I came across blog posts suggesting not to use eval mostly as it can lead > to un-secure code. So wanted to check should I put efforts in solving this > with 'eval' or not. Not an option now. I will explain my problem in next > question. > >> >> > c. If indeed, I have to evaluate a string containing dots, how to do >> > in the above scenario? >> >> The object whose attribute you're trying to access should be there in >> the locals or globals and then should have an attribute with the given >> name. It will work then. >> [...] >> > yes. If my above observation is correct, this is clear to me. I will try to > explain my problem: > > I have a list of strings ( say ['aaa', 'bbb', '4.5-'] ) and I want to check > if an expression (say 'aa') is a substring of any of this item. > > Simply: all([ item for item in ['aaa', 'bbb', '4.5-'] if 'aa' in item]) > ==> gives True as 'aa' is a substring of 'aaa'. > > But my expression can be a logical expression like 'aa or bb', 'aa and > bbb', 'aaa and 4.5' etc. > > This works in my above implementation. If we assume mapping object from > above. Writing it again here for ease. > >> class SimpleMapping: >> def __init__(self, items): >> self._items = items >> >> def __getitem__(self, subitem): >> for item in self._items: >> if subitem in item: >> return True >> return False > >>>> mapping = SimpleMapping(set(['aaa', 'bbb', '4.5-'])) > >>>> eval('aa and bb', {}, mapping) > True # since both > are substring >>>> eval('aa and bbb', {}, mapping) > True # again since > both are substring >>>> eval('aa and bbbb', {}, mapping) > False # 'bbbb' > fails. > > So till now it works fine for my case. But in case if I want to check for > '4.5' in this. > >>>> eval('aaaa or bbbb or 4.5') > 4.5 # Fails for > 'aaaa', fails for 'bbbb' but evaluates '4.5' as 4.5. Something I don't > want. It should be > checking 4.5 against mapping and I want a boolean True here. > > If I am unclear, I will repeat my problem again. > > Problem: How can I evaluate a logical expression, in python where > expression contains a dot ('.'). > > Analysis: First thing strike in my mind is to use eval but that fails on > expression with a dot. My tries are: > > *Try A:* I was thinking something like, transform '.' to '#' (or anything > else). For eg. > > 'aaaa or bbbb or 4.5' becomes 'aaaa or bbbb or 4#5'. > Now if eval('4#5') goes to check inside our mapping we are good. We can > transform back and evaluate. But sadly eval('4#5') gives 4. Tried with many > characters, any hits here? > > *Try B:* Other option is extracting operators out of string ( by list > comprehension or using regular expression) and operator on these string > components. > Is there any direct way to get logical operators from string. I found (c for > c in s if c in '+-/*()_') to get mathematical operators. > > I will try this option tonight. > > Sorry for long reply and redundant answer but I wanted to be clear. If I > was able to explain properly can you suggest anything here? > > Thanks & Regard > Alok > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- Cordially, Noufal http://nibrahim.net.in From noufal at nibrahim.net.in Mon Oct 27 17:38:13 2014 From: noufal at nibrahim.net.in (Noufal Ibrahim KV) Date: Mon, 27 Oct 2014 22:08:13 +0530 Subject: [BangPypers] eval (was: BangPypers Digest, Vol 86, Issue 16) In-Reply-To: (Okan bhan's message of "Mon, 27 Oct 2014 21:17:28 +0530") References: Message-ID: <87a94headm.fsf_-_@nibrahim.net.in> Please ignore my earlier reply to your email. I hit send by accident. Please edit the subject line when you're replying to a digest. On Mon, Oct 27 2014, Okan bhan wrote: [...] >> 2. A mapping object is similar to a dictionary. It should >> return the actual object if you try to access it. Not a boolean True >> or False. >> > Agree with you. Ideally it should have returned object and I can test > by `if obj` or `if not obj`. Lets assume for now I want to continue > with this. I didn't understand what you mean by this. What are you attempting to test with the `if` statements? And what do you want to continue with? >> The mapping objects given are specifications of the locals and globals >> in which you will evaluate your string. Consult help("eval") for more >> information. >> >> eval(source[, globals[, locals]]) -> value >> > Makes sense. So essentially I'm trying to evaluate and expression > ('foo' or 'foo and bar') against a local mapping. Not fully confident > but I can see the use of locals & globals here. Every statement needs an evaluation context. Suppose I ask what the result of the statement `x+2` is, you need a context which provides the value of `x` to be able to answer meaningfully. Python has two such contexts. First is the local context which is inside the function and the second is the global context which is at the module level. Without these, the source referred to above cannot be `eval`uated. [...] > That is strange, I'm still getting 5.6 as result. I tried on different > python versions as well. What version of Python are you using? [...] >> 5.6 is not an attribute access. 5.6 is is a floating point number. aa.a >> is an attribute access. It will first return False for `aa` since there >> is no such key and your code returns False and then try to access `a` in >> the Boolean which, predictably, fails. >> > Big thanks for this. Let me explain what, I understood here. Lets say > statement we want to evaluate is `eval(expression)`. Python starts > checking 'expression' against each datatype starting from int -> float > -> str. For all native datatypes, it will return corresponding > result. Finally if it doesn't matches any of native types, tries to > access against mapping(or any other object in local or global scope). This is a theory that explains the observations but I can't fully endorse your wording. Statements like "Python starts *checking* 'expression' against each *datatype* *starting* from int -> float -> str" is too slipshod for my tastes. Expressions (and I use this to mean the expr_stmt in the grammar[1]), have to be evaluated. A variable is an expression and it is evaluated by a symbol lookup. It is looked up first in the local and on failure, in the global context. > Which is the reason, >>> type(eval('5.6')) is float >>> type(eval("'5.6'") is str (expression is under double quotes). > > For the case of eval('aa.a'), it first tries to match 'aa'. This is not any > native type so goes to check in mapping and finds it True. Then tries to > find attribute 'a' of returned type (a boolean). Hence boolean object has > no attribute 'a'. More or less but it doesn't try to "match" `aa`. The expression first tokenised. You can see this. 1,0-1,2: NAME 'aa' 1,2-1,3: OP '.' 1,3-1,4: NAME 'a' 2,0-2,0: ENDMARKER '' This will get reduced into an expression and then be evaluated. The `aa` is looked up and then the semantics indicate that an attribute lookup should take place. [...] > I came across blog posts suggesting not to use eval mostly as it can lead > to un-secure code. So wanted to check should I put efforts in solving this > with 'eval' or not. Not an option now. I will explain my problem in next > question. evaling code which you have complete control over and which you generate is as safe as general code (although trickier to debug). If there's some tainted data in the string that you eval, the effects might be unpredictable. [...] > yes. If my above observation is correct, this is clear to me. I will try to > explain my problem: > > I have a list of strings ( say ['aaa', 'bbb', '4.5-'] ) and I want to check > if an expression (say 'aa') is a substring of any of this item. > > Simply: all([ item for item in ['aaa', 'bbb', '4.5-'] if 'aa' in item]) > ==> gives True as 'aa' is a substring of 'aaa'. Fair enough. That makes sense. > But my expression can be a logical expression like 'aa or bb', 'aa and > bbb', 'aaa and 4.5' etc. I'd do this by creating a predicate function e.g. def test(x): 'aa' in x or 'bb' in x and then all(item for item in ['aaa', 'bbb', '4.5-'] if test(item)) > This works in my above implementation. If we assume mapping object from > above. Writing it again here for ease. > >> class SimpleMapping: >> def __init__(self, items): >> self._items = items >> >> def __getitem__(self, subitem): >> for item in self._items: >> if subitem in item: >> return True >> return False > >>>> mapping = SimpleMapping(set(['aaa', 'bbb', '4.5-'])) > >>>> eval('aa and bb', {}, mapping) > True # since both > are substring >>>> eval('aa and bbb', {}, mapping) > True # again since > both are substring >>>> eval('aa and bbbb', {}, mapping) > False # 'bbbb' > fails. Okay. I think I see what you're trying to do. You're creating something like a mapping which contains these strings and then evaling a boolean expression which just does a lookup. This works but it contorted and hard to read/maintain. I wouldn't do it this way. I'd use a predicate. > So till now it works fine for my case. But in case if I want to check for > '4.5' in this. > >>>> eval('aaaa or bbbb or 4.5') > 4.5 # Fails for > 'aaaa', fails for 'bbbb' but evaluates '4.5' as 4.5. Something I don't > want. It should be > checking 4.5 against mapping and I want a boolean True here. > > If I am unclear, I will repeat my problem again. Eval is not suited for the problem. I suppose you could do some quoting magic to take care of this but, like I said, it just makes it more and more contorted. When you eval something, it's treated as a piece of python code. You however want to check for strings. > Problem: How can I evaluate a logical expression, in python where > expression contains a dot ('.'). This is not a complete statement. file1.opened and file2.opened is a logical expression which has [...] > Sorry for long reply and redundant answer but I wanted to be clear. If I > was able to explain properly can you suggest anything here? [...] I'd use the predicate approach. Footnotes: [1] https://docs.python.org/2/reference/grammar.html -- Cordially, Noufal http://nibrahim.net.in From arvindkhadri at gmail.com Wed Oct 29 11:26:27 2014 From: arvindkhadri at gmail.com (Arvind K) Date: Wed, 29 Oct 2014 15:56:27 +0530 Subject: [BangPypers] [JOBS] Servelots is hiring a backend stack web developer Message-ID: Hi, Servelots[0] is looking for a developer with 2-3 years of experience in building web applications using python. Please spread the word. [0]: http://servelots.com From tanuj at toptalent.in Thu Oct 30 12:11:21 2014 From: tanuj at toptalent.in (Tanuj Deshpande) Date: Thu, 30 Oct 2014 16:41:21 +0530 Subject: [BangPypers] (no subject) Message-ID: Hi, Gigstart, Gurgaon is looking for Python Developer. If interested, Please follow the link below. https://www.toptalent.in/job/3476/python-developer-intern-new-delhi-india/ Thanks, Tanuj.