Re: python
It seems like that python was already installed in your computer. Please check . On 11 January 2016 at 14:45, Sean Melville wrote: > I don't believe it's xp, it's a new laptop > > > >> On 11 Jan 2016, at 20:33, Cameron Simpson wrote: >> >>> On 11Jan2016 19:17, Sean Melville wrote: >>> I've downloaded python 3.5.1 but when I try and open it always says that I >>> have to either uninstall it, repair it or modify it. However, I've tried >>> all of them and it still doesn't work. >> >> On what operating system are you trying to install it? >> >> If you are using XP you need to download Python 3.4; Python 3.5 is not >> compatible with it. >> >> Cheers, >> Cameron Simpson > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Need help with this asap.
Create a class called BankAccount
Create a constructor that takes in an integer and assigns this to a `balance`
property.
Create a method called `deposit` that takes in cash deposit amount and updates
the balance accordingly.
Create a method called `withdraw` that takes in cash withdrawal amount and
updates the balance accordingly. if amount is greater than balance return
`"invalid transaction"`
Create a subclass MinimumBalanceAccount of the BankAccount class.
This was my solution and I still got error. What should I do.
class BankAccount:
def __init__(self, initial_amount):
self.balance = initial_amount
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance>= amount:
self.balance -= amount
else:
print('invalid transaction')
a1 = BankAccount (90)
a1.deposit(90)
a1.withdraw(40)
a1.withdraw(1000)
class MinimumBalanceAccount(BankAccount):
def __init__(self):
BankAccount.__init__(self)
Please help me.
--
https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
On 12/01/16 07:13, Cameron Simpson wrote: On 11Jan2016 23:55, Erik wrote: Is it complaining about that, or is it because the 'for' loop body might be executed zero times? The former. Almost any loop _might_ be executed zero times. Compilers and linters etc should only complain if they can prove the loop is always executed zero times. Sure, but Skip was thinking he'd found a bug - I was just raising the possibility that the bug could have been that the loop was (incorrectly) determined to be executed zero times for some reason. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
On Friday, January 8, 2016 at 6:16:49 PM UTC+1, [email protected] wrote: > On Friday, 8 January 2016 17:38:11 UTC+1, [email protected] wrote: > > On Wednesday, 30 December 2015 19:21:32 UTC+1, Won Chang wrote: > > > i have these task which i believe i have done well to some level > > > > > > Create a function get_algorithm_result to implement the algorithm below > > > > > > 1- Get a list of numbers L1, L2, L3LN as argument 2- Assume L1 is the > > > largest, Largest = L1 3- Take next number Li from the list and do the > > > following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last > > > number from the list then 7- return Largest and come out 8- Else repeat > > > same process starting from step 3 > > > > > > Create a function prime_number that does the following Takes as parameter > > > an integer and Returns boolean value true if the value is prime or > > > Returns boolean value false if the value is not prime > > > > > > so i came up with this code below > > > > > > def get_algorithm_result(my_list): > > > if not any(not type(y) is int for y in my_list): > > > largest = 0 > > > for item in range(0,len(my_list)): > > > if largest < my_list[item]: > > > largest = my_list[item] > > > return largest > > > else: > > > > > > return(my_list[-1]) > > > > > > def prime_number(integer): > > > if integer%2==0 and 2!=integer: > > > return False > > > else: > > > return True > > > > > > get_algorithm_result([1, 78, 34, 12, 10, 3]) > > > get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) > > > prime_number(1) > > > prime_number(78) > > > prime_number(11) > > > for the question above, there is a unittes which reads > > > > > > import unittest > > > > > > class AlgorithmTestCases(unittest.TestCase): > > > def test_maximum_number_one(self): > > > result = get_algorithm_result([1, 78, 34, 12, 10, 3]) > > > self.assertEqual(result, 78, msg="Incorrect number") > > > > > > def test_maximum_number_two(self): > > > result = get_algorithm_result(["apples", "oranges", "mangoes", > > > "banana", "zoo"]) > > > self.assertEqual(result, "zoo", msg="Incorrect number") > > > > > > def test_prime_number_one(self): > > > result = prime_number(1) > > > self.assertEqual(result, True, msg="Result is invalid") > > > > > > def test_prime_number_two(self): > > > result = prime_number(78) > > > self.assertEqual(result, False, msg="Result is invalid") > > > > > > def test_prime_number_three(self): > > > result = prime_number(11) > > > self.assertEqual(result, True, msg="Result is invalid") > > > but once i run my code ,it returns error saying Test Spec Failed > > > > > > Your solution failed to pass all the tests > > > what is actually wrong with my code? > > > > I had to use a hack to bypass it, worked and I moved on to next quiz > > > could you please share how you bypassed it? Just return the message instead of printing it. > > On Friday, 8 January 2016 17:38:11 UTC+1, [email protected] wrote: > > On Wednesday, 30 December 2015 19:21:32 UTC+1, Won Chang wrote: > > > i have these task which i believe i have done well to some level > > > > > > Create a function get_algorithm_result to implement the algorithm below > > > > > > 1- Get a list of numbers L1, L2, L3LN as argument 2- Assume L1 is the > > > largest, Largest = L1 3- Take next number Li from the list and do the > > > following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last > > > number from the list then 7- return Largest and come out 8- Else repeat > > > same process starting from step 3 > > > > > > Create a function prime_number that does the following Takes as parameter > > > an integer and Returns boolean value true if the value is prime or > > > Returns boolean value false if the value is not prime > > > > > > so i came up with this code below > > > > > > def get_algorithm_result(my_list): > > > if not any(not type(y) is int for y in my_list): > > > largest = 0 > > > for item in range(0,len(my_list)): > > > if largest < my_list[item]: > > > largest = my_list[item] > > > return largest > > > else: > > > > > > return(my_list[-1]) > > > > > > def prime_number(integer): > > > if integer%2==0 and 2!=integer: > > > return False > > > else: > > > return True > > > > > > get_algorithm_result([1, 78, 34, 12, 10, 3]) > > > get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) > > > prime_number(1) > > > prime_number(78) > > > prime_number(11) > > > for the question above, there is a unittes which reads > > > > > > import unittest > > > > > > class AlgorithmTestCases(unittest.TestCase): > > > def test_maximum_number_one(self): > > > result = get_algorithm_result([1, 78, 34, 12, 10, 3]) > > > self.assertEqual(result, 78, msg="Incorrect number") > > > > > > def test_maximum_number_two(self): > > > resul
Installation
I can't download Python and I need it for class. Any suggestions? Ingram Jansen Banner ID: 830742998 -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: There are no words for how broken everything is
Rick Johnson : > they have these new inventions now called "blogs", maybe you should > sign up for one? "Sign up for a blog?" What does that mean? Is it like creating a computer program or starting a company: you sign up for one? Anyway, why not use Usenet what it is meant for: discussions. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
On 1/11/2016 8:09 PM, Chris Angelico wrote: On Tue, Jan 12, 2016 at 11:55 AM, Bernardo Sulzbach wrote: On Mon, Jan 11, 2016 at 10:14 PM, Chris Angelico wrote: Next IDLE feature request: Can you make it so that, across all platforms, it magically installs PostgreSQL and psycopg2? That would solve so many of my students' problems... I detect an invisible smiley at the end of that. PostgresSQL is not a Python package, hence would need a custom script to download and invoke, and would probably need user clicks anyway, at least on Windows. Does/could psycopg2 have such for installing its dependency? Can psycopg2 be installed with pip? There is an issue (#23551) to make a pip GUI and make it accessible from IDLE. We need someone with both pip and tkinter knowledge to either design and write it or mentor a GSOC student to do so. One written, I would add an IDLE menu item to run it, in a separate process, just as done now with turtledemo. Wouldn't this make the installer much bigger? See invisible smiley ;-). Yes, and it's also completely and utterly inappropriate. But I am seeing a lot of cool magic getting added to Idle. Since I met Python, it's gone from being "well, yeah, Python *does* include a GUI, but it's pretty unexciting compared to others" to "Python includes a pretty decent editor, but it's (unsurprisingly) Python-specific, so I don't use it for multilingual work". Shout-out to Terry and the other Idle devs for the work they've put in. > Thanks! Thank *you*. It is sometimes thankless work. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: There are no words for how broken everything is
On Tue, Jan 12, 2016 at 7:30 PM, Marko Rauhamaa wrote: > Rick Johnson : > >> they have these new inventions now called "blogs", maybe you should >> sign up for one? > > "Sign up for a blog?" What does that mean? > > Is it like creating a computer program or starting a company: you sign > up for one? It means getting someone to put up a sign saying "BLOG". I'm sure you can find professional signwriters in your area. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Tools/libraries to determine the call graph(call flow) of an python program (module/package)
Hi Folks, I am trying to do the following. I have a moderately complex python module/application X, whose source code i have access to. I run X with the following command python x.py ... Internally, x.py callls y.py, which in turn calls z.py, etc etc x.py ---> y.py ---> z.py ---> u.py ---> v.py Is there a python library/tool/module , to which i give input the start point of X, x.py and the input arguments, arg1, arg2, ..., argn and which can come up with the call graph of X I have tried looking at pycallgraph[0], but havent had much luck with it. 0. https://pypi.python.org/pypi/pycallgraph Any suggestions,advice, pointers welcome. Thanks a ton, ashish "Talk is cheap. Show me the code." - Linus Torvalds [ https://lkml.org/lkml/2000/8/25/132 ] -- https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
Apologies for self-replying On 12/01/16 08:24, Erik wrote: On 12/01/16 07:13, Cameron Simpson wrote: The former. Almost any loop _might_ be executed zero times. Compilers and linters etc should only complain if they can prove the loop is always executed zero times. I was just raising the possibility that the bug could have been that the loop was (incorrectly) determined to be executed zero times for some reason. Having just read it again, I note that Skip said he'd changed the |= to something different (and I've since read the solution to the question). I had misread what Skip said to mean he had added a new line _after_ the 'for' loop which touched the variable. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
On Tue, Jan 12, 2016 at 7:27 PM, Terry Reedy wrote:
> On 1/11/2016 8:09 PM, Chris Angelico wrote:
>>
>> On Tue, Jan 12, 2016 at 11:55 AM, Bernardo Sulzbach
>> wrote:
>>>
>>> On Mon, Jan 11, 2016 at 10:14 PM, Chris Angelico
>>> wrote:
Next IDLE feature request: Can you make it so that, across all
platforms, it magically installs PostgreSQL and psycopg2? That would
solve so many of my students' problems...
>
>
> I detect an invisible smiley at the end of that.
>
> PostgresSQL is not a Python package, hence would need a custom script to
> download and invoke, and would probably need user clicks anyway, at least on
> Windows. Does/could psycopg2 have such for installing its dependency?
>
> Can psycopg2 be installed with pip? There is an issue (#23551) to make a
> pip GUI and make it accessible from IDLE. We need someone with both pip and
> tkinter knowledge to either design and write it or mentor a GSOC student to
> do so. One written, I would add an IDLE menu item to run it, in a separate
> process, just as done now with turtledemo.
Yes, invisible smiley... but with a hint of truth too. Obviously
installing PostgreSQL itself is outside the scope of IDLE, but
psycopg2 is indeed pip-installable... except that it isn't always, on
Windows, because wheels aren't available for all versions. (There's no
Python 3.5 wheel yet; at least, I can't see one on PyPI.) So what I'm
really looking for isn't an IDLE feature but a Python packaging
feature - some people have talked about setting up build farms that
can produce wheels for people.
Hmm. I just tried this, and actually, there's some possibly
low-hanging fruit. (Tested on Python 3.4.3 as 3.5 can't install
psycopg2 anyway.)
>>> import pip; pip.main(["install","psycopg2"])
This produces a rather messy display, because pip.main seems to assume
that writing carriage returns to the console will result in the
display nicely overwriting (producing a moving progress bar as the
file gets downloaded). If IDLE can't handle carriage returns as such,
an easy fix would be to simply display them as complete lines; it
would be more verbose than the normal console behaviour, but not as
ugly.
A couple of other random thoughts from this experiment.
* Going to python.org and pointing the mouse at the download link got
me 3.5.1 32-bit. This is on Google Chrome on a Windows 7 64-bit VM.
* Instead of pip.main(["install","psycopg2"]), I'd like to be able to
say pip.install("psycopg2"). In fact, I might take that to the pip
folks as a suggestion.
* The performance difference between "import pip" on 3.4.3 and 3.5.1
was dramatic! I don't know whether it's CPython that's been sped up or
pip itself, but it's awesome!
There's some kind of issue between pip and Idle that means that
installing a non-wheel blows up with an exception:
Traceback (most recent call last):
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\basecommand.py",
line 211, in main
status = self.run(options, args)
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\commands\install.py",
line 294, in run
requirement_set.prepare_files(finder)
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\req\req_set.py",
line 334, in prepare_files
functools.partial(self._prepare_file, finder))
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\req\req_set.py",
line 321, in _walk_req_to_install
more_reqs = handler(req_to_install)
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\req\req_set.py",
line 505, in _prepare_file
abstract_dist.prep_for_dist()
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\req\req_set.py",
line 123, in prep_for_dist
self.req_to_install.run_egg_info()
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\req\req_install.py",
line 410, in run_egg_info
command_desc='python setup.py egg_info')
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\utils\__init__.py",
line 711, in call_subprocess
line = console_to_str(proc.stdout.readline())
File
"C:\Users\Rosuav\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pip\compat\__init__.py",
line 47, in console_to_str
return s.decode(sys.__stdout__.encoding)
AttributeError: 'NoneType' object has no attribute 'encoding'
Maybe calling pip.main just isn't a supported thing, but it'd be nice
if there were _some_ way to do this, even without a fancy GUI.
How much of this is worth doing anything about, and how much is "hey,
you're hacking around calling a command-line tool from inside a GUI,
and stuff ain't a'gonna work right"?
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: Need help with this asap.
ifeanyioprah--- via Python-list wrote:
> Create a class called BankAccount
> Create a constructor that takes in an integer and assigns this to a
`balance` property.
> Create a method called `deposit` that takes in cash deposit amount and
updates the balance accordingly.
> Create a method called `withdraw` that takes in cash withdrawal amount and
updates the balance accordingly. if amount is greater than balance return
`"invalid transaction"`
Return or print? You print.
> Create a subclass MinimumBalanceAccount of the BankAccount class.
I would suppose that such a MinimumBalanceAccount needs a way to specify the
minimum balance (in the initializer) and to ensure (both initially and in
the withdraw() method) that the account actually has that minimum balance.
> This was my solution and I still got error. What should I do.
> class BankAccount:
> def __init__(self, initial_amount):
> self.balance = initial_amount
> def deposit(self, amount):
> self.balance += amount
> def withdraw(self, amount):
> if self.balance>= amount:
> self.balance -= amount
> else:
> print('invalid transaction')
> a1 = BankAccount (90)
> a1.deposit(90)
> a1.withdraw(40)
> a1.withdraw(1000)
> class MinimumBalanceAccount(BankAccount):
> def __init__(self):
> BankAccount.__init__(self)
>
--
https://mail.python.org/mailman/listinfo/python-list
modifying parts of a urlparse.SplitResult
I can successfully parse my URLs. However, I'd like to modify a part then reassemble them. However, like tuples, the parts appear to be unmodifiable >>> URL = 'http://foo/path1/path2/?fragment=foo' >>> import urlparse >>> u = urlparse.urlparse(URL) >>> u ParseResult(scheme='http', netloc='foo', path='/path1/path2/', params='', query='fragment=foo', fragment='') >>> u.query 'fragment=foo' >>> u.query = 'blah=baz' Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute The best I've been able to come up with is >>> u = urlparse.urlsplit(URL) >>> lst = list(u) # can't manipulate the tuple directly >>> lst[3] = "bar=baz" # 3 = query-string index >>> urlparse.urlunsplit(lst) 'http://foo/path1/path2/?bar=baz' It takes knowing that "3" is the magic index (documented, but not given some named-constant in urlparse) for the query-string. Is there some better, clearer, or more Pythonic way to do this? -tkc (sorry if this is a dupe post, as I got an SMTP bounce/error from mail.python.org stating "service currently unavailable") -- https://mail.python.org/mailman/listinfo/python-list
Re: modifying parts of a urlparse.SplitResult
Tim Chase wrote:
> I can successfully parse my URLs. However, I'd like to modify a part
> then reassemble them. However, like tuples, the parts appear to be
> unmodifiable
>
> >>> URL = 'http://foo/path1/path2/?fragment=foo'
> >>> import urlparse
> >>> u = urlparse.urlparse(URL)
> >>> u
> ParseResult(scheme='http', netloc='foo', path='/path1/path2/',
> params='', query='fragment=foo', fragment='')
> >>> u.query
> 'fragment=foo'
> >>> u.query = 'blah=baz'
> Traceback (most recent call last):
> File "", line 1, in
> AttributeError: can't set attribute
>
> The best I've been able to come up with is
>
> >>> u = urlparse.urlsplit(URL)
> >>> lst = list(u) # can't manipulate the tuple directly
> >>> lst[3] = "bar=baz" # 3 = query-string index
> >>> urlparse.urlunsplit(lst)
> 'http://foo/path1/path2/?bar=baz'
>
> It takes knowing that "3" is the magic index (documented, but not
> given some named-constant in urlparse) for the query-string. Is
> there some better, clearer, or more Pythonic way to do this?
To allow more fieldnames namedtuples use method names starting with an
underscore. You can safely use them, they are not private. So:
>>> pr = urlparse.urlparse("http://foo/path1/path2/?fragment=foo";)
>>> urlparse.urlunparse(pr._replace(query="bar=baz"))
'http://foo/path1/path2/?bar=baz'
--
https://mail.python.org/mailman/listinfo/python-list
Re: Installation
On Mon, Jan 11, 2016 at 8:30 PM, Jansen, Ingram L < [email protected]> wrote: > > I can't download Python and I need it for class. Any suggestions? > > drop the class? ;) But more seriously, what OS, what version of Python, what did you try, what happened? > > Ingram Jansen > Banner ID: 830742998 > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays -- https://mail.python.org/mailman/listinfo/python-list
Re: [egenix-info] ANN: Python Meeting Düsseldorf - 19.01.2016
On 12.01.2016 10:53, eGenix Team: M.-A. Lemburg wrote: > [This announcement is in German since it targets a local user group > meeting in Düsseldorf, Germany] > > > > ANKÜNDIGUNG > > Python Meeting Düsseldorf > > http://pyddf.de/ > >Ein Treffen von Python Enthusiasten und Interessierten > in ungezwungener Atmosphäre. > > Mittwoch, 21.10.2015, 18:00 Uhr Sorry, the correct date is: Dienstag, 19.01.2016, 18:00 Uhr > Raum 1, 2.OG im Bürgerhaus Stadtteilzentrum Bilk > Düsseldorfer Arcaden, Bachstr. 145, 40217 Düsseldorf > > Diese Nachricht ist auch online verfügbar: > http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2016-01-19 > > > NEUIGKEITEN > > * Bereits angemeldete Vorträge: > >Jens Diemer >"DragonPy - Dragon 32 Emulator in Python" > >Charlie Clark >"Statische Code-Analyse mit Quantified Code" > >Marc-Andre Lemburg >"MicroPython auf dem BBC MicroBit" > >Weitere Vorträge können gerne noch angemeldet werden: [email protected] > > * Startzeit und Ort: > >Wir treffen uns um 18:00 Uhr im Bürgerhaus in den Düsseldorfer >Arcaden. > >Das Bürgerhaus teilt sich den Eingang mit dem Schwimmbad >und befindet sich an der Seite der Tiefgarageneinfahrt der >Düsseldorfer Arcaden. > >Über dem Eingang steht ein großes Schwimm'in Bilk >Logo. Hinter der Tür direkt links zu den zwei Aufzügen, >dann in den 2. Stock hochfahren. Der Eingang zum Raum 1 >liegt direkt links, wenn man aus dem Aufzug kommt. > >Google Street View: http://bit.ly/11sCfiw > > > > EINLEITUNG > > Das Python Meeting Düsseldorf ist eine regelmäßige Veranstaltung in > Düsseldorf, die sich an Python Begeisterte aus der Region wendet: > > * http://pyddf.de/ > > Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal, > auf dem wir die Vorträge nach den Meetings veröffentlichen: > > * http://www.youtube.com/pyddf/ > > Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld, > in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf: > > * http://www.egenix.com/ > * http://www.clark-consulting.eu/ > > > > PROGRAMM > > Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space > und Lightning Talks, wobei die Gewitter bei uns auch schon mal > 20 Minuten dauern können ;-). > > Lightning Talks können vorher angemeldet werden, oder auch > spontan während des Treffens eingebracht werden. Ein Beamer mit > XGA Auflösung steht zur Verfügung. Folien bitte als PDF auf USB > Stick mitbringen. > > Lightning Talk Anmeldung bitte formlos per EMail an [email protected] > > > > KOSTENBETEILIGUNG > > Das Python Meeting Düsseldorf wird von Python Nutzern für Python > Nutzer veranstaltet. Um die Kosten zumindest teilweise zu > refinanzieren, bitten wir die Teilnehmer um einen Beitrag > in Höhe von EUR 10,00 inkl. 19% Mwst, Schüler und Studenten > zahlen EUR 5,00 inkl. 19% Mwst. > > Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen. > > > > ANMELDUNG > > Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir > bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung > eingegangen. Es erleichtert uns allerdings die Planung. > > Meeting Anmeldung bitte formlos per EMail an [email protected] > > > > WEITERE INFORMATIONEN > > Weitere Informationen finden Sie auf der Webseite des Meetings: > > http://pyddf.de/ > > Mit freundlichen Grüßen, > -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Jan 12 2016) >>> Python Projects, Coaching and Consulting ... http://www.egenix.com/ >>> Python Database Interfaces ... http://products.egenix.com/ >>> Plone/Zope Database Interfaces ... http://zope.egenix.com/ ::: We implement business ideas - efficiently in both time and costs ::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ http://www.malemburg.com/ -- https://mail.python.org/mailman/listinfo/python-list
ANN: Python Meeting Düsseldorf - 19.01.2016
[This announcement is in German since it targets a local user group meeting in Düsseldorf, Germany] ANKÜNDIGUNG Python Meeting Düsseldorf http://pyddf.de/ Ein Treffen von Python Enthusiasten und Interessierten in ungezwungener Atmosphäre. Mittwoch, 21.10.2015, 18:00 Uhr Raum 1, 2.OG im Bürgerhaus Stadtteilzentrum Bilk Düsseldorfer Arcaden, Bachstr. 145, 40217 Düsseldorf Diese Nachricht ist auch online verfügbar: http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2016-01-19 NEUIGKEITEN * Bereits angemeldete Vorträge: Jens Diemer "DragonPy - Dragon 32 Emulator in Python" Charlie Clark "Statische Code-Analyse mit Quantified Code" Marc-Andre Lemburg "MicroPython auf dem BBC MicroBit" Weitere Vorträge können gerne noch angemeldet werden: [email protected] * Startzeit und Ort: Wir treffen uns um 18:00 Uhr im Bürgerhaus in den Düsseldorfer Arcaden. Das Bürgerhaus teilt sich den Eingang mit dem Schwimmbad und befindet sich an der Seite der Tiefgarageneinfahrt der Düsseldorfer Arcaden. Über dem Eingang steht ein großes Schwimm'in Bilk Logo. Hinter der Tür direkt links zu den zwei Aufzügen, dann in den 2. Stock hochfahren. Der Eingang zum Raum 1 liegt direkt links, wenn man aus dem Aufzug kommt. Google Street View: http://bit.ly/11sCfiw EINLEITUNG Das Python Meeting Düsseldorf ist eine regelmäßige Veranstaltung in Düsseldorf, die sich an Python Begeisterte aus der Region wendet: * http://pyddf.de/ Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal, auf dem wir die Vorträge nach den Meetings veröffentlichen: * http://www.youtube.com/pyddf/ Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld, in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf: * http://www.egenix.com/ * http://www.clark-consulting.eu/ PROGRAMM Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space und Lightning Talks, wobei die Gewitter bei uns auch schon mal 20 Minuten dauern können ;-). Lightning Talks können vorher angemeldet werden, oder auch spontan während des Treffens eingebracht werden. Ein Beamer mit XGA Auflösung steht zur Verfügung. Folien bitte als PDF auf USB Stick mitbringen. Lightning Talk Anmeldung bitte formlos per EMail an [email protected] KOSTENBETEILIGUNG Das Python Meeting Düsseldorf wird von Python Nutzern für Python Nutzer veranstaltet. Um die Kosten zumindest teilweise zu refinanzieren, bitten wir die Teilnehmer um einen Beitrag in Höhe von EUR 10,00 inkl. 19% Mwst, Schüler und Studenten zahlen EUR 5,00 inkl. 19% Mwst. Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen. ANMELDUNG Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung eingegangen. Es erleichtert uns allerdings die Planung. Meeting Anmeldung bitte formlos per EMail an [email protected] WEITERE INFORMATIONEN Weitere Informationen finden Sie auf der Webseite des Meetings: http://pyddf.de/ Mit freundlichen Grüßen, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Jan 12 2016) >>> Python Projects, Coaching and Consulting ... http://www.egenix.com/ >>> Python Database Interfaces ... http://products.egenix.com/ >>> Plone/Zope Database Interfaces ... http://zope.egenix.com/ ::: We implement business ideas - efficiently in both time and costs ::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ http://www.malemburg.com/ -- https://mail.python.org/mailman/listinfo/python-list
Re: modifying parts of a urlparse.SplitResult
On 2016-01-12 13:46, Peter Otten wrote:
> Tim Chase wrote:
> > >>> u = urlparse.urlsplit(URL)
> > >>> lst = list(u) # can't manipulate the tuple directly
> > >>> lst[3] = "bar=baz" # 3 = query-string index
> > >>> urlparse.urlunsplit(lst)
> > 'http://foo/path1/path2/?bar=baz'
> >
> > It takes knowing that "3" is the magic index (documented, but not
> > given some named-constant in urlparse) for the query-string. Is
> > there some better, clearer, or more Pythonic way to do this?
>
> To allow more fieldnames namedtuples use method names starting with
> an underscore. You can safely use them, they are not private. So:
>
> >>> pr = urlparse.urlparse("http://foo/path1/path2/?fragment=foo";)
> >>> urlparse.urlunparse(pr._replace(query="bar=baz"))
> 'http://foo/path1/path2/?bar=baz'
Much nicer. Thanks!
Off to improve my code.
-tkc
--
https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
You're still struggling with this question because you didn't take your time to read the previous comments here , the solution to this and other question has being posted long ago before new year here , just read previous comments. Remember don't use print , instead use return . -- https://mail.python.org/mailman/listinfo/python-list
Re: What use of these _ prefix members?
On 2016-01-10, Peter Otten <[email protected]> wrote: class Derived(Base): > ... def _init(self, x): > ... super()._init(x) > ... print("do something else with", x) > ... Derived(42) > do something with 42 > do something else with 42 ><__main__.Derived object at 0x7f8e6b3e9b70> > I think you are doing inheritance wrong. AFAIK you should call directly the __init__() of the parent class, and pass *args and **kwargs instead. Except for that, yes, the _init would be conventionally private. Not enforced by name mangling though. -- https://mail.python.org/mailman/listinfo/python-list
Re: What use of these _ prefix members?
Someone else posting as "me" wrote: > On 2016-01-10, Peter Otten <[email protected]> wrote: > class Derived(Base): >> ... def _init(self, x): >> ... super()._init(x) >> ... print("do something else with", x) >> ... > Derived(42) >> do something with 42 >> do something else with 42 >><__main__.Derived object at 0x7f8e6b3e9b70> >> > > I think you are doing inheritance wrong. If by "you" you mean "me" -- the above sample is an illustration of the pattern I expected to see elsewhere in the software Robert was quoting, not an endorsement. I have now looked into the hmmlearn source, and it turns out that _init() is invoked by the fit() method rather than the initializer. But... > AFAIK you should call directly the __init__() of the parent class, and > pass *args and **kwargs instead. you sometimes want to break initialisation or any other method into distinct steps that don't make sense stand-alone: class Foo: def method(...) self._one(...) self._two(...) self._three(...) That way subclasses have the option to override only _two() instead of method() and users of Foo won't try to invoke _two(...) on its own. I think this is a good approach. What arguments you need to accept and/or pass on is a question that you can decide depending on the actual use-case. I use *args, **kwargs only if function is very generic because it makes code hard to follow. > Except for that, yes, the _init would be conventionally private. Not > enforced by name mangling though. -- https://mail.python.org/mailman/listinfo/python-list
Re: What use of these _ prefix members?
On Tue, Jan 12, 2016 at 9:12 AM, me wrote: > On 2016-01-10, Peter Otten <[email protected]> wrote: > class Derived(Base): > > ... def _init(self, x): > > ... super()._init(x) > > ... print("do something else with", x) > > ... > Derived(42) > > do something with 42 > > do something else with 42 > ><__main__.Derived object at 0x7f8e6b3e9b70> > > > > I think you are doing inheritance wrong. > There's nothing "wrong" about this, and there are times this type of pattern is justified. Sure, *this* example doesn't make sense to do it this way, but this is just an illustrative example. I would even call this type of pattern pythonic. > AFAIK you should call directly the __init__() of the parent class, and > > pass *args and **kwargs instead. > Sometimes there's no need to call __init__ on the parent class directly, and the base class's __init__ is sufficient for the derived class. And perhaps initialization requires numerous "steps" that are easiest to grok when split out into different, private sub-methods. For example: class Derived(Base): def __init__(self, arg1, arg2, arg3): self._initial_object_setup() self._process_arg1(arg1) self._process_arg23(arg2, arg3) self._postprocess_new_object() This makes it clear what is involved in the initialization of the new object. And it allows the functionality to be split up into more atomic units. It also has the added benefit of subclasses being able to more selectively override base class functionality. Suppose Derived only needs to change how it reacts to arg1 -- all Derived needs to implement directly is _process_arg1. This reduces code duplication and improves maintainability, and is a pattern I've used myself and like enough to use again (not necessarily in __init__, but outside of being automatically called during construction I don't see anything else inherently "specialer" about __init__ than any other method). All the best, Jason -- https://mail.python.org/mailman/listinfo/python-list
Re: Python installation in windows
On 11 January 2016 at 20:16, Cameron Simpson wrote: > On 11Jan2016 07:19, rusi wrote: >> >> On Monday, January 11, 2016 at 6:32:14 PM UTC+5:30, navneet bhatele wrote: >>> >>> I have been trying to install the "python-3.5.1-amd64-webinstall " many >>> times and the Set up failed is shown up with named 0*80070002 - file >>> doesn't exist in dialog box >> >> >> Which windows? >> XP and 3.5 are not compatible >> For XP use 3.4 > > > I am not a Windows user, but this question occurs a lot. > > Is this cryptic message a missing dependency of the installer or of Python. > Because if it is Python surely we should be doing potential users a favour > and mentioning this 3.5 vs XP (and earlier?) issue in nice human friendly > prose instead of complaining about an obscure missing library file? > > As things stand, many users infer that they have a corrupt or broken > download, not that they needed a different version of Python. I think there are several different issues to do with Python 3.5 and Windows. Firstly support for Windows XP was dropped and 3.5 was made in a way that is incompatible with XP. However initially neither the download page nor the installer were warning XP users leading to a lot of confusion. I thought this was suppose to have been fixed in 3.5.1 though so the installer should now warn that it won't work on XP. Secondly the Windows builds of 3.5 are now compiled using VS2015 and I believe the installer itself has had something of an overhaul. This seems to have caused a number of different problems. One problem is that the newer VS2015 runtime requires the installation of some dll from Microsoft. So some users are getting error messages about a missing dll. The error message quoted above is something else though. I can't tell but it seems as if there are a number of distinct issues caused by the significant changes to Python 3.5 on Windows. > Should this be raised on python-dev? Probably better to go for bugs.python.org. There's a few 3.5/Windows issues already there. Not sure if this one's already listed. -- Oscar -- https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
On Mon, Jan 11, 2016 at 6:04 PM, Skip Montanaro
wrote:
> Sorry, I should have been explicit. prob_dates (the actual argument of the
> call) is a set. As far as I know pylint does no type inference, so pylint
> can't tell if the LHS and RHS of the |= operator are appropriate, nor can
> it tell if it has an update() method.
>
> Before writing, I had more-or-less concluded I had hit a bug, but in my
> experience when I hit something I think is a bug, it's not. It's me.
> Terry's reply convinced me that I had hit something.
>
> Something else just occurred to me. I should have tried disassembling the
> two versions of the function. Here's the output near prob_dates.update()
> call:
>
> 14
>
>62 LOAD_FAST3 (prob_dates)
> 65 LOAD_ATTR6 (update)
> 68 LOAD_GLOBAL 7 (compare_prices)
> 71 LOAD_CONST 3 ('E:%s')
> 74 LOAD_FAST5 (sym)
> 77 BINARY_MODULO
> 78 LOAD_FAST0 (cx1)
> 81 LOAD_FAST1 (cx2)
> 84 LOAD_FAST2 (cx3)
> 87 CALL_FUNCTION4
> 90 CALL_FUNCTION1
>
> Here's how the |= version disassembles in that region:
>
> 20
>
> 62 LOAD_FAST3 (prob_dates)
> 65 LOAD_GLOBAL 6 (compare_prices)
> 68 LOAD_CONST 3 ('E:%s')
> 71 LOAD_FAST5 (sym)
> 74 BINARY_MODULO
> 75 LOAD_FAST0 (cx1)
> 78 LOAD_FAST1 (cx2)
> 81 LOAD_FAST2 (cx3)
> 84 CALL_FUNCTION4
> 87 INPLACE_OR
> 88 STORE_FAST 3 (prob_dates)
>
> I think what's throwing pylint is that last
> STORE_FAST. That tells pylint the argument is ignored.
I may be wrong, but I believe pylint just looks at the AST, not the opcodes.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to remove item from heap efficiently?
On 12.01.2016 03:48, Cem Karan wrote: Jumping in late, but... If you want something that 'just works', you can use HeapDict: http://stutzbachenterprises.com/ I've used it in the past, and it works quite well. I haven't tested its asymptotic performance though, so you might want to check into that. Thanks for replying here. I've come across these types of wrappers/re-implementations of heapq as well when researching this issue. :) Unfortunately, they don't solve the underlying issue at hand which is: "remove item from heap with unknown index" and be efficient at it (by not using _heapq C implementation). So, I thought I did another wrapper. ;) It at least uses _heapq (if available otherwise heapq) and lets you remove items without violating the invariant in O(log n). I am going to make that open-source on pypi and see what people think of it. Best, Sven -- https://mail.python.org/mailman/listinfo/python-list
Re: Python installation in windows
On Tue, Jan 12, 2016 at 9:15 AM, Oscar Benjamin wrote: > > I thought this was suppose to have been fixed in 3.5.1 though so the installer > should now warn that it won't work on XP. The CRT update also requires service pack 1 on Windows 7 and service pack 2 on Vista. 3.5.1's installer was updated to check for a supported operating system. On an XP system the error message should be "Windows Vista SP2 or later is required to continue installation". > I believe the installer itself has had something of an overhaul. It was rewritten completely. -- https://mail.python.org/mailman/listinfo/python-list
subscripting Python 3 dicts/getting the only value in a Python 3 dict
Hi all,
Seemingly simple problem:
There is a case in my code where I know a dictionary has only one item in it. I
want to get the value of that item, whatever the key is.
In Python2 I'd write:
>>> d = {"Wilf's Cafe": 1}
>>> d.values()[0]
1
and that'd be an end to it.
In Python 3:
>>> d = {"Wilf's Cafe": 1}
>>> d.values()[0]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'dict_values' object does not support indexing
"Wilf's Cafe"
>>> d[list(d)[0]]
1
>>> for k in d:
... value = d[k]
... break
...
>>> value
1
>>> list(d.values())[0]
1
None of this feels like the "one, and preferably only one, obvious way to do
it" we all strive for. Any other ideas?
Thanks,
Nick
--
https://mail.python.org/mailman/listinfo/python-list
use Python and an outlook: protocol URL to bring up a specific email
Hi all
a little OS/windows specific, I'm afraid:
In Windows, there exists a part-supported 'outlook protocol' to obtain and use
email references within Outlook as URL. You have to go through various
shenanagins to enable this and to get Outlook to give you access to the URLs -
see for instance:
http://www.slipstick.com/problems/outlook-missing-outlook-protocol/
http://superuser.com/questions/834019/using-outlook-protocol-open-current-instance-of-outlook-not-new-instance
http://www.davidtan.org/create-hyperlinks-to-outlook-messages-folders-contacts-events/
Having gone through all of this I get a refernce URL on my clipboard or
whatever:
"outlook:BB1BBDFACA3A4D41A98037A1D85A8DA50700E6FBFC004227134D97632785EE69C220003C0208DEA1DAC09B3B9C648E4597BE2A013A6E8B8426F87CCA"
(This refers to a particular email in Outlook)
What I want to do is then use Python to invoke this URL to cause Outlook to
bring up the referenced email. I'm stumbling here; I've tried urllib.urlopen(),
and os.startfile(), but I am getting errors from urllib in either case:
def open_unknown(self, fullurl, data=None):
"""Overridable interface to open unknown URL type."""
type, url = splittype(fullurl)
raise IOError, ('url error', 'unknown url type', type)
ie. the 'outlook' protocol is unknown.
I happy to carve some code without using urllib, but I am not clear what I
actually need to do to 'open' such a URL using this protocol. FWIW I can paste
this URL into Windows Explorer and I get the referenced email popping up ;-)
Thanks for any pointers
Regards
Jon N
--
https://mail.python.org/mailman/listinfo/python-list
RE: subscripting Python 3 dicts/getting the only value in a Python 3 dict
> Hi all,
>
> Seemingly simple problem:
>
> There is a case in my code where I know a dictionary has only one item in it.
> I want to get the value of that item, whatever the key is.
>
> In Python2 I'd write:
>
> >>> d = {"Wilf's Cafe": 1}
> >>> d.values()[0]
> 1
The equivalent in Python 3 is `list(d.values())[0]`
> None of this feels like the "one, and preferably only one, obvious way to do
> it" we all strive for. Any other ideas?
If you feel like doing that, `for v in d.values(): pass` will set `v` to your
value. But it's a bit cryptic, so you can probably resort to the list()
alternative above :)
- Emanuel
--
https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On Wed, Jan 13, 2016 at 3:50 AM, Nick Mellor wrote:
> There is a case in my code where I know a dictionary has only one item in it.
> I want to get the value of that item, whatever the key is.
>
> In Python2 I'd write:
>
d = {"Wilf's Cafe": 1}
d.values()[0]
> 1
>
> and that'd be an end to it.
>
> In Python 3:
>
d = {"Wilf's Cafe": 1}
d.values()[0]
> Traceback (most recent call last):
> File "", line 1, in
> TypeError: 'dict_values' object does not support indexing
> "Wilf's Cafe"
d[list(d)[0]]
> 1
You could try:
next(iter(d.values()))
but honestly, this isn't all that common a situation, so I'm not
surprised there's no really simple and clean way to do it.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
On Wed, Jan 13, 2016 at 3:51 AM, jkn wrote: > I happy to carve some code without using urllib, but I am not clear what I > actually need to do to 'open' such a URL using this protocol. FWIW I can paste > this URL into Windows Explorer and I get the referenced email popping up ;-) > What happens if you invoke the 'start' command using subprocess? subprocess.check_call(["start", url]) In theory, that should be equivalent to pasting it into Explorer. In theory. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On 1/12/2016 11:50 AM, Nick Mellor wrote:
Hi all,
Seemingly simple problem:
There is a case in my code where I know a dictionary has only one item in it. I
want to get the value of that item, whatever the key is.
In Python2 I'd write:
d = {"Wilf's Cafe": 1}
d.values()[0]
1
and that'd be an end to it.
In Python 3:
d = {"Wilf's Cafe": 1}
d.values()[0]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'dict_values' object does not support indexing
The intended use of dict views: "Dictionary views can be iterated over
to yield their respective data, and support membership tests:"
"Wilf's Cafe"
d[list(d)[0]]
1
for k in d:
... value = d[k]
... break
...
value
1
list(d.values())[0]
1
None of this feels like the "one, and preferably only one,
> obvious way to do it" we all strive for. Any other ideas?
Using the values views at intended (as an iterable):
>>> dv = d.values()
>>> next(iter(dv))
1
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Intentions aside, next(iter(...)) seems the most pythonic you can get about this anyway. Just in case you happen not to need the dictionary anymore, d.popitem()[1] does the trick. -- https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
Hi Chris On Tuesday, January 12, 2016 at 5:11:18 PM UTC, Chris Angelico wrote: > On Wed, Jan 13, 2016 at 3:51 AM, jkn wrote: > > I happy to carve some code without using urllib, but I am not clear what I > > actually need to do to 'open' such a URL using this protocol. FWIW I can > > paste > > this URL into Windows Explorer and I get the referenced email popping up ;-) > > > > What happens if you invoke the 'start' command using subprocess? > > subprocess.check_call(["start", url]) > > In theory, that should be equivalent to pasting it into Explorer. In theory. > > ChrisA I'll try that, but (typically!) I found some things that worked shortly after posting... These both work: PROTOCOL = "outlook:" TEST_URL = "BB1BBDFACA3A... 8426F87CCA" # elided for example import os os.startfile(PROTOCOL + TEST_URL, 'open') # second parameter not needed # and import win32api win32api.ShellExecute(0, 'open', PROTOCOL + TEST_URL, "", "", 0) I thought I had already tried the first one, not sure what happened. Sorry for the noise... Cheers Jon N -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Nick Mellor wrote:
> Hi all,
>
> Seemingly simple problem:
>
> There is a case in my code where I know a dictionary has only one item in
> it. I want to get the value of that item, whatever the key is.
>
> In Python2 I'd write:
>
d = {"Wilf's Cafe": 1}
d.values()[0]
> 1
>
> and that'd be an end to it.
>
> In Python 3:
>
d = {"Wilf's Cafe": 1}
d.values()[0]
> Traceback (most recent call last):
> File "", line 1, in
> TypeError: 'dict_values' object does not support indexing
> "Wilf's Cafe"
d[list(d)[0]]
> 1
>
for k in d:
> ... value = d[k]
> ... break
> ...
value
> 1
>
list(d.values())[0]
> 1
>
> None of this feels like the "one, and preferably only one, obvious way to
> do it" we all strive for. Any other ideas?
If there is exactly one item you can unpack:
>>> d = {"Wilf's Cafe": 1}
>>> k, = d.values()
>>> k
1
--
https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On Tue, Jan 12, 2016 at 10:12 AM, Terry Reedy wrote:
> Using the values views at intended (as an iterable):
>
dv = d.values()
next(iter(dv))
> 1
Good coding practice also dictates that whenever next is called, the
potential StopIteration exception must be caught unless it is clearly
intended to be propagated up to some generator. So more fully, this
should be something like:
dv = iter(d.values())
try:
next(dv)
except StopIteration:
raise IndexError("d is empty")
At which point it may be desirable to extract that into a utility function.
--
https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
On Tue, Jan 12, 2016 at 11:10 AM, Chris Angelico wrote:
> On Wed, Jan 13, 2016 at 3:51 AM, jkn wrote:
>> I happy to carve some code without using urllib, but I am not clear what I
>> actually need to do to 'open' such a URL using this protocol. FWIW I can
>> paste
>> this URL into Windows Explorer and I get the referenced email popping up ;-)
>
> What happens if you invoke the 'start' command using subprocess?
>
> subprocess.check_call(["start", url])
>
> In theory, that should be equivalent to pasting it into Explorer. In theory.
start is a shell command. It also has a quirk that the first quoted
argument is the window title. Here's the correct call:
subprocess.check_call('start "title" "%s"' % url, shell=True)
That said, since no arguments are being passed the simpler and more
secure way to call ShellExecute in this case is os.startfile(url).
--
https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
I created an issue for the pylint folks: https://github.com/PyCQA/pylint/issues/774 Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Nick Mellor writes:
> Hi all,
>
> Seemingly simple problem:
>
> There is a case in my code where I know a dictionary has only one item
> in it. I want to get the value of that item, whatever the key is.
>
> In Python2 I'd write:
>
d = {"Wilf's Cafe": 1}
d.values()[0]
> 1
>
> and that'd be an end to it.
>
> In Python 3:
If you are happy to give the sole value a name:
>>> shoe = dict(it=math.pi)
>>> [o] = shoe.values()
>>> o
3.141592653589793
You might be able to use * to pass the sole value to a function:
>>> print(*shoe.values())
3.141592653589793
But the most readable thing might be to have a function that extracts
the sole value by whatever means:
>>> def sole(d): [o] = d.values() ; return o
...
>>> sole(shoe)
3.141592653589793
--
https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
On Wed, Jan 13, 2016 at 4:37 AM, eryk sun wrote:
> On Tue, Jan 12, 2016 at 11:10 AM, Chris Angelico wrote:
>> On Wed, Jan 13, 2016 at 3:51 AM, jkn wrote:
>>> I happy to carve some code without using urllib, but I am not clear what I
>>> actually need to do to 'open' such a URL using this protocol. FWIW I can
>>> paste
>>> this URL into Windows Explorer and I get the referenced email popping up ;-)
>>
>> What happens if you invoke the 'start' command using subprocess?
>>
>> subprocess.check_call(["start", url])
>>
>> In theory, that should be equivalent to pasting it into Explorer. In theory.
>
> start is a shell command. It also has a quirk that the first quoted
> argument is the window title. Here's the correct call:
>
> subprocess.check_call('start "title" "%s"' % url, shell=True)
Is that properly escaped to handle any arbitrary URL? I doubt it.
Do you actually need shell=True? I would strongly recommend using the
form that I used, unless it can be proven that that doesn't work.
> That said, since no arguments are being passed the simpler and more
> secure way to call ShellExecute in this case is os.startfile(url).
Yes. The OP mentioned having tried this, though, so I went for an alternative.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
Am 12.01.16 um 18:52 schrieb Chris Angelico:
On Wed, Jan 13, 2016 at 4:37 AM, eryk sun wrote:
start is a shell command. It also has a quirk that the first quoted
argument is the window title. Here's the correct call:
subprocess.check_call('start "title" "%s"' % url, shell=True)
Is that properly escaped to handle any arbitrary URL? I doubt it.
Do you actually need shell=True? I would strongly recommend using the
form that I used, unless it can be proven that that doesn't work.
As stated, start is not an executable on Windows, but it is a built-in
command of cmd.exe. And thus it has very quirky quotation rules. This is
unlike Linux, where "xdg-open" is a shell script, and OSX, where "open"
is a binary executable.
Christian
--
https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Ian Kelly wrote:
> On Tue, Jan 12, 2016 at 10:12 AM, Terry Reedy wrote:
>> Using the values views at intended (as an iterable):
>>
> dv = d.values()
> next(iter(dv))
>> 1
>
> Good coding practice also dictates that whenever next is called, the
> potential StopIteration exception must be caught unless it is clearly
> intended to be propagated up to some generator.
Even then you should be prepared for
https://docs.python.org/dev/whatsnew/3.5.html#pep-479-change-stopiteration-handling-inside-generators
> So more fully, this
> should be something like:
>
> dv = iter(d.values())
> try:
> next(dv)
> except StopIteration:
> raise IndexError("d is empty")
>
> At which point it may be desirable to extract that into a utility
> function.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
On 2016-01-12, Bernardo Sulzbach wrote: > On Mon, Jan 11, 2016 at 10:14 PM, Chris Angelico wrote: >> >> Next IDLE feature request: Can you make it so that, across all >> platforms, it magically installs PostgreSQL and psycopg2? That would >> solve so many of my students' problems... >> > > Wouldn't this make the installer much bigger? Whoosh! -- Grant Edwards grant.b.edwardsYow! I feel like I am at sharing a ``CORN-DOG'' gmail.comwith NIKITA KHRUSCHEV ... -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On Tue, Jan 12, 2016 at 3:32 PM, Peter Otten <[email protected]> wrote: > > If there is exactly one item you can unpack: > d = {"Wilf's Cafe": 1} k, = d.values() k > 1 > I personally don't like that trailing comma, it just looks wrong there. But this is very neat. -- Bernardo Sulzbach -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Bernardo Sulzbach wrote: > On Tue, Jan 12, 2016 at 3:32 PM, Peter Otten <[email protected]> wrote: >> >> If there is exactly one item you can unpack: >> > d = {"Wilf's Cafe": 1} > k, = d.values() > k >> 1 >> > > I personally don't like that trailing comma, it just looks wrong > there. But this is very neat. > [k] = d.values() works the same. I used the tuple here to keep it consistent with all other cases where the brackets are superfluous, like [foo, *bar] = ... foo, *bar = ... etc. -- https://mail.python.org/mailman/listinfo/python-list
Re: use Python and an outlook: protocol URL to bring up a specific email
On Tue, Jan 12, 2016 at 11:52 AM, Chris Angelico wrote: > Is that properly escaped to handle any arbitrary URL? I doubt it. subprocess doesn't know how to quote a command line for the Windows shell, which doesn't follow the rules used by subprocess.list2cmdline. To make matters worse, one often has to follow both sets of rules or even some arbitrary rules used by an executable. > Do you actually need shell=True? I would strongly recommend using the > form that I used, unless it can be proven that that doesn't work. AFAIK, the "start" command has been built in to the shell since cmd.exe originated on OS/2 in like 1987. It was enhanced when cmd.exe was ported to Win32 for NT 3.1. -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
I saw it in another answer. next(iter(d)) is still the winner. This resembles a list just too much, making the coder's intent harder to understand. This is **very** subjective, of course. -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Jussi Piitulainen : > But the most readable thing might be to have a function that extracts > the sole value by whatever means: > >>>> def sole(d): [o] = d.values() ; return o >... >>>> sole(shoe) >3.141592653589793 In the same vein: >>> def sole(d): ... for o in d.values(): ... return o ... >>> sole(shoe) 3.141592653589793 Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
Marko Rauhamaa writes: > Jussi Piitulainen: > >> But the most readable thing might be to have a function that extracts >> the sole value by whatever means: >> >>>>> def sole(d): [o] = d.values() ; return o >>... >>>>> sole(shoe) >>3.141592653589793 > > In the same vein: > >>>> def sole(d): >... for o in d.values(): >... return o >... >>>> sole(shoe) >3.141592653589793 Tuple assignment has a useful side effect that all other methods present in this thread lack: it raises an exception if the number of dictionary entries is not exactly one. -- https://mail.python.org/mailman/listinfo/python-list
It looks like one function not tested by pytest
Hi,
I modify a test suite, and simplified to the below content.
I am interested in function:
test_bad_covariance_type()
I think that it tests for wrong type input, i.e.
'badcovariance_type'
will generate error, which is expected. Thus, it passes test.
When a correct type, such as 'diag', is given, there will be no error
generated. pytest will declare a failure.
Unfortunately, it will always pass the pytest for both cases.
What is wrong with my code or my understanding?
Thanks,
//
from __future__ import absolute_import
from unittest import TestCase
import numpy as np
import pytest
from hmmlearn import hmm
from . import log_likelihood_increasing, make_covar_matrix, normalized
class GaussianHMMTestMixin(object):
covariance_type = None # set by subclasses
def setUp(self):
self.prng = prng = np.random.RandomState(10)
self.n_components = n_components = 3
self.n_features = n_features = 3
self.startprob = prng.rand(n_components)
self.startprob = self.startprob / self.startprob.sum()
self.transmat = prng.rand(n_components, n_components)
self.transmat /= np.tile(self.transmat.sum(axis=1)[:, np.newaxis],
(1, n_components))
self.means = prng.randint(-20, 20, (n_components, n_features))
self.covars = dict(
(cv_type, make_covar_matrix(cv_type, n_components, n_features))
for cv_type in ["spherical", "tied", "diag", "full"])
self.expanded_covars = {
'spherical': [np.eye(n_features) * cov
for cov in self.covars['spherical']],
'diag': [np.diag(cov) for cov in self.covars['diag']],
'tied': [self.covars['tied']] * n_components,
'full': self.covars['full'],
}
def test_bad_covariance_type(self):
with pytest.raises(ValueError):
#h = hmm.GaussianHMM(20, covariance_type='badcovariance_type')
h = hmm.GaussianHMM(covariance_type='diag')
h.means_ = self.means
h.covars_ = []
h.startprob_ = self.startprob
h.transmat_ = self.transmat
h._check()
def test_fit(self, params='stmc', n_iter=5, **kwargs):
h = hmm.GaussianHMM(self.n_components, self.covariance_type)
h.startprob_ = self.startprob
h.transmat_ = normalized(
self.transmat + np.diag(self.prng.rand(self.n_components)), 1)
h.means_ = 20 * self.means
h.covars_ = self.covars[self.covariance_type]
lengths = [10] * 10
X, _state_sequence = h.sample(sum(lengths), random_state=self.prng)
# Mess up the parameters and see if we can re-learn them.
# TODO: change the params and uncomment the check
h.fit(X, lengths=lengths)
class TestGaussianHMMWithSphericalCovars(GaussianHMMTestMixin, TestCase):
covariance_type = 'spherical'
def test_fit_startprob_and_transmat(self):
self.test_fit('st')
def test_bad_covariance_type0(self):
self.test_bad_covariance_type()
--
https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
Chris Angelico wrote: So start simplistic, and then look into it like this: "Hey, see how you're doing this five times? There HAS to be a better way!" (With acknowledgement to Raymond Hettinger.) That gave me visions of a little animated cartoon of Raymond popping up in the corner of the screen, offering to write some code for me. The next big IDLE feature...? -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Tue, Jan 12, 2016 at 7:01 PM, Gregory Ewing wrote: > Chris Angelico wrote: >> >> So start simplistic, and then look >> into it like this: "Hey, see how you're doing this five times? There >> HAS to be a better way!" (With acknowledgement to Raymond Hettinger.) > > > That gave me visions of a little animated cartoon of > Raymond popping up in the corner of the screen, offering > to write some code for me. The next big IDLE feature...? > The Windows paperclip strikes back! -- Bernardo Sulzbach -- https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Mon, Jan 11, 2016 at 5:53 PM, Bernardo Sulzbach wrote: > I have never gone "seriously OO" with Python though. I never wrote > from scratch an application with more than 10 classes as far as I can > remember. However, I would suppose that the interpreter can handle > thousands of user-defined classes simultaneously. In Python, a class is just an object, so the only limit on how many classes the interpreter can handle simultaneously is available memory. However, if you have deeply nested inheritance graphs then you could start to see performance issues on method calls, since the entire inheritance graph potentially has to be traversed in order to find the method. -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
Terry Reedy at 2016/1/12 UTC+8 3:56:03PM wrote: > Revamping IDLE to 1. use ttk widgets and 2. become a modern single > window app with multiple panes, including a tabbed editor pane, is a > goal for 2016. That will be great, I'm looking forward to it. By the way, when I was playing around with the IDLE editor yesterday, I had noticed that during the time the "Search Dialog" was opened, "Find Next" button will not highlight the item searched, unless the dialog was closed. --Jach Fong -- https://mail.python.org/mailman/listinfo/python-list
Re: It looks like one function not tested by pytest
On Tuesday, January 12, 2016 at 3:36:13 PM UTC-5, Robert wrote:
> Hi,
>
> I modify a test suite, and simplified to the below content.
> I am interested in function:
> test_bad_covariance_type()
>
> I think that it tests for wrong type input, i.e.
> 'badcovariance_type'
> will generate error, which is expected. Thus, it passes test.
>
> When a correct type, such as 'diag', is given, there will be no error
> generated. pytest will declare a failure.
>
>
> Unfortunately, it will always pass the pytest for both cases.
>
> What is wrong with my code or my understanding?
>
>
> Thanks,
>
>
>
>
> //
> from __future__ import absolute_import
>
> from unittest import TestCase
>
> import numpy as np
> import pytest
>
> from hmmlearn import hmm
>
> from . import log_likelihood_increasing, make_covar_matrix, normalized
>
>
> class GaussianHMMTestMixin(object):
> covariance_type = None # set by subclasses
>
> def setUp(self):
> self.prng = prng = np.random.RandomState(10)
> self.n_components = n_components = 3
> self.n_features = n_features = 3
> self.startprob = prng.rand(n_components)
> self.startprob = self.startprob / self.startprob.sum()
> self.transmat = prng.rand(n_components, n_components)
> self.transmat /= np.tile(self.transmat.sum(axis=1)[:, np.newaxis],
> (1, n_components))
> self.means = prng.randint(-20, 20, (n_components, n_features))
> self.covars = dict(
> (cv_type, make_covar_matrix(cv_type, n_components, n_features))
> for cv_type in ["spherical", "tied", "diag", "full"])
> self.expanded_covars = {
> 'spherical': [np.eye(n_features) * cov
> for cov in self.covars['spherical']],
> 'diag': [np.diag(cov) for cov in self.covars['diag']],
> 'tied': [self.covars['tied']] * n_components,
> 'full': self.covars['full'],
> }
>
> def test_bad_covariance_type(self):
> with pytest.raises(ValueError):
> #h = hmm.GaussianHMM(20, covariance_type='badcovariance_type')
> h = hmm.GaussianHMM(covariance_type='diag')
> h.means_ = self.means
> h.covars_ = []
> h.startprob_ = self.startprob
> h.transmat_ = self.transmat
> h._check()
>
> def test_fit(self, params='stmc', n_iter=5, **kwargs):
> h = hmm.GaussianHMM(self.n_components, self.covariance_type)
> h.startprob_ = self.startprob
> h.transmat_ = normalized(
> self.transmat + np.diag(self.prng.rand(self.n_components)), 1)
> h.means_ = 20 * self.means
> h.covars_ = self.covars[self.covariance_type]
>
> lengths = [10] * 10
> X, _state_sequence = h.sample(sum(lengths), random_state=self.prng)
>
> # Mess up the parameters and see if we can re-learn them.
> # TODO: change the params and uncomment the check
> h.fit(X, lengths=lengths)
>
>
>
>
> class TestGaussianHMMWithSphericalCovars(GaussianHMMTestMixin, TestCase):
> covariance_type = 'spherical'
>
> def test_fit_startprob_and_transmat(self):
> self.test_fit('st')
>
> def test_bad_covariance_type0(self):
> self.test_bad_covariance_type()
It turns out that it always raises error, because there are other errors
besides the covariance_type object. That is, pytest works as expected.
Thanks,
--
https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On Wed, 13 Jan 2016 03:50 am, Nick Mellor wrote: > Hi all, > > Seemingly simple problem: > > There is a case in my code where I know a dictionary has only one item in > it. I want to get the value of that item, whatever the key is. [snip examples] > None of this feels like the "one, and preferably only one, obvious way to > do it" we all strive for. Any other ideas? That's because this is a somewhat weird case. A dict with only one item that you don't know the key of? Who does that? (Well, apart from you, obviously.) Three solutions: item = d.popitem()[1] # But this modifies the dict. # Use tuple rather than list for efficiency. item = tuple(d.values())[0] Probably the best solution, because it will conveniently raise an exception if your assumption that the dict has exactly one item is wrong: item, = d.values() # Note the comma after "item". The comma turns the assignment into sequence unpacking. Normally we would write something like this: a, b, c, d = four_items but you can unpack a sequence of one item too. If you really want to make it obvious that the comma isn't a typo: (item,) = d.values() -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
[email protected] at 2016/1/月12 4:29:08PM wrote: > IDLE ? > I need less than 10 seconds to make it crash. Unwittingly or intentionally? > The interesting aspect is not only to show that it crashes, > the very interesting point is to explain why it is crashing. Can you tell us (in a separate subject title)? I am willing to learn every aspects of Python. --Jach Fong -- https://mail.python.org/mailman/listinfo/python-list
Re: subscripting Python 3 dicts/getting the only value in a Python 3 dict
On Wed, 13 Jan 2016 06:12 am, Bernardo Sulzbach wrote:
> I saw it in another answer. next(iter(d)) is still the winner.
Except that doesn't return the *value*, it returns the *key*.
py> d = {'key': 'value'}
py> next(iter(d))
'key'
To get the value:
py> next(iter(d.values()))
'value'
> This resembles a list just too much, making the coder's intent harder
> to understand. This is **very** subjective, of course.
I'm sorry, I don't understand what you mean by "resembles a list"? What
does? In what way?
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Wed, 13 Jan 2016 11:18 am, Ian Kelly wrote: > On Mon, Jan 11, 2016 at 5:53 PM, Bernardo Sulzbach > wrote: >> I have never gone "seriously OO" with Python though. I never wrote >> from scratch an application with more than 10 classes as far as I can >> remember. However, I would suppose that the interpreter can handle >> thousands of user-defined classes simultaneously. > > In Python, a class is just an object, so the only limit on how many > classes the interpreter can handle simultaneously is available memory. > > However, if you have deeply nested inheritance graphs then you could > start to see performance issues on method calls, since the entire > inheritance graph potentially has to be traversed in order to find the > method. I'm sure Ian knows this already, but for the benefit of others... Python is not Java: http://dirtsimple.org/2004/12/python-is-not-java.html And Java is not Python either: http://dirtsimple.org/2004/12/java-is-not-python-either.html -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
On Wed, Jan 13, 2016 at 12:27 PM, wrote: > [email protected] at 2016/1/月12 4:29:08PM wrote: >> IDLE ? >> I need less than 10 seconds to make it crash. > > Unwittingly or intentionally? > >> The interesting aspect is not only to show that it crashes, >> the very interesting point is to explain why it is crashing. > > Can you tell us (in a separate subject title)? I am willing to learn every > aspects of Python. Take no notice of the troll. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Data Entry
Hi All
I have written a small web app using cgi for testing for changes to data from a
python script that does a lot of database updating depending on certain
conditions
form = cgi.FieldStorage()
cRefNo = form.getvalue('refno')
cElectSupp = form.getvalue('electsupp')
print('Electrical Supplier : '%cElectSupp)
If i change the value from origin to origin energy and save - the value updated
to the database is correct but when the page is re displayed it only
shows origin in the text field - as if it ignores everything after the space.
How do I make it display the full name.
Cheers
Colin
--
https://mail.python.org/mailman/listinfo/python-list
Re: Data Entry
On Wed, Jan 13, 2016 at 12:52 PM, wrote: > If i change the value from origin to origin energy and save - the value > updated to the database is correct but when the page is re displayed it only > shows origin in the text field - as if it ignores everything after the space. > > How do I make it display the full name. > To set a multi-word value as an HTML attribute, you'll need to put quotes around it. You might be able to get away with using %r instead of %s, or even just "%s", but proper escaping would be the best way. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Which Python editor has this feature?
On Wed, 13 Jan 2016 12:27 pm, [email protected] wrote: > [email protected] at 2016/1/月12 4:29:08PM wrote: >> IDLE ? >> I need less than 10 seconds to make it crash. > > Unwittingly or intentionally? > >> The interesting aspect is not only to show that it crashes, >> the very interesting point is to explain why it is crashing. > > Can you tell us (in a separate subject title)? I am willing to learn every > aspects of Python. Pay no attention to wxjmfauth, he is our resident troll who is obsessed with Python's Unicode implementation. When he says "make it crash", he means "raise an exception", which is absolutely trivial. We can all make Python raise an exception in a fraction of a second: 1/0 will do it. Or if you prefer to stick to unicode: u'£'.encode('ascii') wxjmfauth's obsession started with an alpha release of Python 3.3 that had a small performance decrease for some operations on non-ASCII characters under some circumstances. He has taken this tiny decrease in performance as proof of some grand conspiracy that the Python developers hate non-English speaking Europeans (he never seems to care about Asians or other non-Latin based characters, only French and other European ones) and that this small performance decrease shows that Python can't do Unicode. I think that is fair to say that he is what the English call "a nutter". -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Data Entry
On Wednesday, January 13, 2016 at 9:52:17 AM UTC+8, [email protected] wrote: > Hi All > > I have written a small web app using cgi for testing for changes to data from > a python script that does a lot of database updating depending on certain > conditions > > form = cgi.FieldStorage() > cRefNo = form.getvalue('refno') > > > cElectSupp = form.getvalue('electsupp') > > > print('Electrical Supplier : type="text" name="electsupp" value=%s>'%cElectSupp) > > > If i change the value from origin to origin energy and save - the value > updated to the database is correct but when the page is re displayed it only > shows origin in the text field - as if it ignores everything after the space. > > How do I make it display the full name. > > Cheers > > Colin Hi Chris %r worked a treat thanks Colin -- https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Sunday, January 10, 2016 at 1:00:13 PM UTC+5:30, Arshpreet Singh wrote: > Hello Friends, I am quite new to OOP(object oriented Programming), I did some > projects with python which includes Data-Analysis, Flask Web Development and > some simple scripts. > > I have only one question which is bothering me most of the time, When I will > get the need to use Classes in Python? Or in other way is there any real-life > example where you can tell me this problem/solution is kind of impossible in > Python without Classes? I think the answers so far dont cover two complementary sides to this question: 1. Python the LANGUAGE, is rather even-handed in paradigm choice: Choose OO, imperative, functional or whatever style pleases/suits you 2. Python LIBRARIES however need to make committing choices. Users of those then need to align with these. egs 1. Majority of basic python is functional; eg stuff in os module 2. Some things need object creation and method call eg for re-s you need to know about and to use re objects, match objects etc 3. Then there are things that are naturally used by inheriting and extending eg Basehttpserver is typically used via inheritance To use these you need to know basic OO 4. Then there may be things whose natural usage needs multiple inheritance [cant think of examples] So as others have said, in principle you dont need to go beyond 1. Unfortunately when you are using non-trivial libraries you are a user both of python and the library and so the library-author's paradigm choices are a given for you -- https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Wednesday 13 January 2016 14:36, Rustom Mody wrote: > 1. Python the LANGUAGE, is rather even-handed in paradigm choice: Choose > OO, imperative, functional or whatever style pleases/suits you > 2. Python LIBRARIES however need to make committing choices. Users of > those then need to align with these. I don't think that second one is necessarily correct. Look at the random module: it is based on an OOP design, with classes random.Random and random.SystemRandom doing the real work. But most people don't use them directly, they use the procedural interface random.random, random.choice, random.seed etc. -- Steve -- https://mail.python.org/mailman/listinfo/python-list
Re: When I need classes?
On Wednesday, January 13, 2016 at 10:57:23 AM UTC+5:30, Steven D'Aprano wrote: > On Wednesday 13 January 2016 14:36, Rustom Mody wrote: > > > 1. Python the LANGUAGE, is rather even-handed in paradigm choice: Choose > > OO, imperative, functional or whatever style pleases/suits you > > 2. Python LIBRARIES however need to make committing choices. Users of > > those then need to align with these. > > I don't think that second one is necessarily correct. Look at the random > module: it is based on an OOP design, with classes random.Random and > random.SystemRandom doing the real work. But most people don't use them > directly, they use the procedural interface random.random, random.choice, > random.seed etc. > Yes one can have more or less degrees of freedom. Are infinite degrees possible? I believe not. eg My example of re is strictly not correct: can use strings instead of re objects Can use findall instead of search/match and avoid groping around in opaque match objects So you may conclude that the re module allows these degrees of freedom But you cant bold res all the way into the syntax of the language (eg perl/awk) Anyway these are side points My main point is that when you sit on top of heavy-duty many-layered libraries (worse frameworks... OP seems to be trying Kivy) then you have to align with the opinionatedness of all the layers down to python. Of course that is modulo the leakiness of the abstractions. eg mostly python programmers do not need to know the underlying C... Mostly... And then someone asks about id/is/performance... -- https://mail.python.org/mailman/listinfo/python-list
Stop writing Python 4 incompatible code
Quote:
With the end of support for Python 2 on the horizon (in 2020),
many package developers have made their packages compatible
with both Python 2 and Python 3 by using constructs such as:
if sys.version_info[0] == 2:
# Python 2 code
else:
# Python 3 code
[...]
Another example of problematic code is the following:
if six.PY2:
# Python 2 code
elif six.PY3:
# Python 3 code
In this case, no code will get executed on Python 4 at all!
[end quote]
http://astrofrog.github.io/blog/2016/01/12/stop-writing-python-4-
incompatible-code/
or http://tinyurl.com/jskt54s
Better still, don't do version checks *at all*. There is almost never any
need for a version check. Better is to use feature detection:
try:
xrange # Succeeds in Python 2.
except NameError:
xrange = range
Not only is this almost entirely future-proof[1] and avoids overly-specific
version tests, but if your code happens to find itself running in a
customized environment which has already monkey-patched builtins to re-add
xrange, the first lookup will succeed and no extra work need be done.
You can be extremely fine-grained too:
try:
casefold = str.casefold # Succeeds in Python 3.3 or better
else:
casefold = str.lower # Poor Man's case-folding.
# Or if you prefer:
def casefold(s):
...
About the only thing I use version checking for is to decide which prompt I
want to use:
if sys.version_info[0] >= 3 and os.name == 'posix':
# Make the main prompt bold in Python 3. This probably won't
# work on Windows, put it should(?) work on any POSIX system.
sys.ps1 = '\001\x1b[1m\002py> \001\x1b[0m\002'
else:
sys.ps1 = 'py> '
In Python 3, that highlights the prompt py> in bold.
You can detect the return type:
if isinstance(map(len, []), list):
print("Python 2 version of map")
else:
# Python 3, or Python 2 with future_builtins.
print("Python 3 version of map")
and even the number and kind of arguments:
try:
sorted([], cmp=None)
except TypeError:
print("use key not cmp in Python 3")
_sorted = sorted
def sorted(L, cmp=None):
if cmp is None:
return _sorted(L)
return _sorted(L, key=functools.cmp_to_key(cmp))
So remember, use feature detection, not version checking.
[1] It might fail if some distant version of Python adds an xrange which
does something completely unexpected, or if it removes range; but surely
nobody can be expected to write forward-compatible code in the face of
changes of that magnitude.
--
Steve
--
https://mail.python.org/mailman/listinfo/python-list
