OrderedDict with kwds
For regular dicts I like to use the dict() function because the code is easier to write and read. But OrderedDict() is not equivalent to dict(): In the docstring of collections.OrderedDict it says "keyword arguments are not recommended because their insertion order is arbitrary" (https://github.com/python/cpython/blob/3.6/Lib/collections/__init__.py) It took me while to realize that. What is the best way to use keywords to create an ordered dict, while maintaining insertion order? Below is OrderedDict.__init__. Would the insertion order be preserved if the last line were to be replaced with: if kwds: for k, v in kwds.items(): self[k] = v if args: self.__update(*args) # no **kwds! ### class OrderedDict(dict): 'Dictionary that remembers insertion order' def __init__(*args, **kwds): '''Initialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if not args: raise TypeError("descriptor '__init__' of 'OrderedDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__hardroot = _Link() self.__root = root = _proxy(self.__hardroot) root.prev = root.next = root self.__map = {} self.__update(*args, **kwds) Thanks! Albert-Jan -- https://mail.python.org/mailman/listinfo/python-list
Re: Turtle window not closing
Harshika Varadhan via Python-list wrote: > I am creating a game where the user inputs a coordinate to place their > piece on a chess board. My code then draws the chess board with a turtle > and fills in the squares in with green where the user can place their next > piece. After the user inputs their first coordinate, the turtle draws the > board, but then the window doesn't close and the program ends up crashing. It probably raises an exception and prints a traceback. That "traceback" contains the location and a description of the error Python encountered in your script and is therefore valuable information that can help you fix your code. If you get a traceback always include it into your mail (use cut-and- paste). > Is there any way to solve this problem?I appreciate your help. My function > for drawing the chess board: def draw_board():t = turtle.Turtle() > t.speed(0)t.ht()t.up()t.goto(-100, -100)t.down() for i in > range(0, 8):for j in range(0, 8):if free_squares[i][j] > == ".":if j != 7:t.fillcolor("green") > t.pencolor("black")t.begin_fill() > for k in range(4):t.forward(50) > t.left(90)t.end_fill() >t.forward(50)if j == 7: > t.fillcolor("green")t.pencolor("black") > t.begin_fill()for k in range(4): > t.forward(50)t.left(90) > t.end_fill()t.right(270) > t.forward(50)t.left(90) > t.forward(350)t.right(180) turtle.bye() Thank you, > Harshi That's pretty unreadable. Please remember to post plain text with line- wrapping turned off next time. > the program ends up crashing. If I were to guess: Did you define the `free_squares` list of lists properly? > but then the window doesn't close Are you running your script from within IDLE? Try starting it from the command line instead. Like turtle IDLE itself is a program written in tkinter, and the separation between editer and user code is not always perfect. -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
On Fri, Apr 21, 2017 at 6:08 PM, Albert-Jan Roskam wrote: > Would the insertion order be preserved if the last line were to be > replaced with: > > if kwds: > for k, v in kwds.items(): > self[k] = v > if args: > self.__update(*args) # no **kwds! The basic problem is that kwds is a regular, unordered dict: def f(**kwds): print(type(kwds)) >>> f() -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
On Sat, Apr 22, 2017 at 3:08 AM, Albert-Jan Roskam wrote: > For regular dicts I like to use the dict() function because the code is > easier to write and read. But OrderedDict() is not equivalent to dict(): > In the docstring of collections.OrderedDict it says "keyword arguments are > not recommended because their insertion order is arbitrary" > (https://github.com/python/cpython/blob/3.6/Lib/collections/__init__.py) > >From Python 3.6, keyword arguments are ordered. So the docstring is outdated. -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
Albert-Jan Roskam wrote: > For regular dicts I like to use the dict() function because the code is > easier to write and read. But OrderedDict() is not equivalent to dict(): > In the docstring of collections.OrderedDict it says "keyword arguments are > not recommended because their insertion order is arbitrary" > (https://github.com/python/cpython/blob/3.6/Lib/collections/__init__.py) > > It took me while to realize that. What is the best way to use keywords to > create an ordered dict, while maintaining insertion order? That's the equivalent to "How can I eat my cake and have it." Once you pass keyword arguments order is inevitably lost $ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))' ['a', 'b'] $ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))' ['a', 'b'] $ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))' ['b', 'a'] in all Python versions prior to 3.6. However, in 3.6 dict keys stay in insertion order, so you don't even need an OrderedDict anymore. Specifically https://docs.python.org/dev/whatsnew/3.6.html """ CPython implementation improvements: ... The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function. """ -- https://mail.python.org/mailman/listinfo/python-list
Re: Bigotry (you win, I give up)
On Friday, April 21, 2017 at 2:38:08 PM UTC+5:30, Antoon Pardon wrote: > Op 20-04-17 om 17:25 schreef Rustom Mody: > > But more importantly thank you for your polite and consistent pointing out > > to > > Ben Finney that his religion-bashing signature lines [many of them] and his > > claims to wish this list be welcoming are way out of sync. > > I don't know. I think a concept like welcoming is too complex, to draw such > simple conclusions. First of all we have to make a choice about the public we > want to be welcoming to. I'm rather confident we can agree we don't want to > be welcoming to bigots on this list. > > Then feeling welcome is not a boolean, people can feel welcome to a different > degree and there are many factors at work. If people tend to react in a > friendly > manner to there co-participants, people generally should feel welcome. A > statment > in a signature that isn't addressing anyone personnaly may give rise to some > irritation but shouldn't make this list feel unwelcome to someone. Generally agree [though I wonder how you will decide what constitutes a 'bigot'. Look at the suggestion in the very subject of these threads] > > Do you think critising any idea in one's signature is enough to conclude that > this person doesn't wish this list to be welcoming? Lets try a thought-experiment: A: Islam is glorious B: Religion is garbage C: Christ is the best Will these statements get equal treatment as spam/as censure etc if they appear on this list? Note that from certain pov, religion-bashing or atheism-lauding are as much pushing some belief-system as pushing an (un)conventional religion More to the point will an anti-semitic view be treated with equal harshness to an anti-Islam/Palestine one? https://mail.python.org/pipermail/python-list/2017-April/720532.html Overall, even though it may be a blunt weapon: Why not just keep out utterly unrelated-to-python stuff? -- https://mail.python.org/mailman/listinfo/python-list
Microsoft now ships Python with SQL Server
https://blogs.technet.microsoft.com/dataplatforminsider/2017/04/19/python-in-sql-server-2017-enhanced-in-database-machine-learning/ Quote: We are excited to share the preview release of in-database analytics and machine learning with Python in SQL Server. Python is one of the most popular languages for data science and has a rich ecosystem of powerful libraries. Starting with the CTP 2.0 release of SQL Server 2017, you can now bring Python-based intelligence to your data in SQL Server. The addition of Python builds on the foundation laid for R Services in SQL Server 2016 and extends that mechanism to include Python support for in-database analytics and machine learning. We are renaming R Services to Machine Learning Services, and R and Python are two options under this feature. /quote -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
How to get Buttons to work
I am busy learning Python and I want to make a simple program that connects to a database to locate the information of Doctors. Now the as far as I can see everything works fine, database connects, info gets displayed, but the buttons don't want to work. Please see code and error below. Any help will be greatly appreciated. Error: Traceback (most recent call last): File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 57, in myapp = MyForm() File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 29, in __init__ QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' ), self.UpdateRecords) AttributeError: 'MyForm' object has no attribute 'UpdateRecords' >>> Code: #CallDoctorLocator import sys from DoctorLocator import * from PyQt4 import QtSql, QtGui #Create Connection to the Database def createConnection(): db = QtSql.QSqlDatabase.addDatabase('QMYSQL') db.setHostName('localhost') db.setDatabaseName('healthcare') db.setUserName('root') db.setPassword('3364834') db.open() print (db.lastError().text()) return True class MyForm(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.model = QtSql.QSqlTableModel(self) self.model.setTable("doctors") self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.model.select() self.ui.tableView.setModel(self.model) QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' ), self.UpdateRecords) QtCore.QObject.connect(self.ui.buttonCancel, QtCore.SIGNAL('clicked()' ), self.CancelChanges) QtCore.QObject.connect(self.ui.buttonAdd, QtCore.SIGNAL('clicked()' ), self.AddRecord) QtCore.QObject.connect(self.ui.buttonDelete, QtCore.SIGNAL('clicked()' ), self.DeleteRecord) QtCore.QObject.connect(self.ui.buttonSearch, QtCore.SIGNAL('clicked()' ), self.SearchRecords) def UpdateRecords(self): self.model.AddRecord() def CancelChanges(self): self.model.revertAll() def UpdateRecords (self): self.model.insertRow(self.ui.tableView.currentIndex().row()) def DeleteRecords(self): self.model.removeRow(self.ui.tableView.currentIndex().row()) self.model.AddRecord() def SearchRecords(self): self.model.setFilter("Name like '" + self.ui.Name.text()+"%'") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) if not createConnection(): sys.exit(1) myapp = MyForm() myapp.show() sys.exit(app.exec_()) -- https://mail.python.org/mailman/listinfo/python-list
Re: How to get Buttons to work
horgan.ant...@gmail.com wrote: > I am busy learning Python and I want to make a simple program that > connects to a database to locate the information of Doctors. Now the as > far as I can see everything works fine, database connects, info gets > displayed, but the buttons don't want to work. Please see code and error > below. > > Any help will be greatly appreciated. > > Error: > > Traceback (most recent call last): > File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 57, in > > myapp = MyForm() > File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 29, in > __init__ > QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' > ), self.UpdateRecords) > AttributeError: 'MyForm' object has no attribute 'UpdateRecords' > Code: > > #CallDoctorLocator import sys from DoctorLocator import * from PyQt4 > #import QtSql, QtGui > > #Create Connection to the Database def createConnection(): > db = QtSql.QSqlDatabase.addDatabase('QMYSQL') > db.setHostName('localhost') > db.setDatabaseName('healthcare') > db.setUserName('root') > db.setPassword('3364834') > db.open() > print (db.lastError().text()) > return True > > class MyForm(QtGui.QDialog): > def __init__(self, parent=None): > QtGui.QWidget.__init__(self, parent) > QtGui.QWidget.__init__(self, parent) > self.ui = Ui_Dialog() > self.ui.setupUi(self) > self.model = QtSql.QSqlTableModel(self) > self.model.setTable("doctors") > self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) > self.model.select() > self.ui.tableView.setModel(self.model) > QtCore.QObject.connect(self.ui.ButtonUpdate, > QtCore.SIGNAL('clicked()' ), self.UpdateRecords) > QtCore.QObject.connect(self.ui.buttonCancel, > QtCore.SIGNAL('clicked()' ), self.CancelChanges) > QtCore.QObject.connect(self.ui.buttonAdd, > QtCore.SIGNAL('clicked()' ), self.AddRecord) > QtCore.QObject.connect(self.ui.buttonDelete, > QtCore.SIGNAL('clicked()' ), self.DeleteRecord) > QtCore.QObject.connect(self.ui.buttonSearch, > QtCore.SIGNAL('clicked()' ), self.SearchRecords) > > > def UpdateRecords(self): > self.model.AddRecord() The above UpdateRecord() method (also the methods that follow) has to be indented to the same level as the __init__() method. As written it is defined as a standalone function. > > def CancelChanges(self): > self.model.revertAll() > > def UpdateRecords (self): > self.model.insertRow(self.ui.tableView.currentIndex().row()) Once the indentation is fixed: you cannot have two methods with the same name. You have to decide if you want the first or the second UpdateRecords() implementation. > > def DeleteRecords(self): > self.model.removeRow(self.ui.tableView.currentIndex().row()) > self.model.AddRecord() > > def SearchRecords(self): > self.model.setFilter("Name like '" + self.ui.Name.text()+"%'") > > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > if not createConnection(): > sys.exit(1) > myapp = MyForm() > myapp.show() > sys.exit(app.exec_()) -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
INADA Naoki writes: > From Python 3.6, keyword arguments are ordered. So the docstring is > outdated. (Thank you, Inada-san, for the implementation!) The announcement of the change specifies that we should not rely on ordered ‘dict’: The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon […]. https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation> So, I would recommend continuing to code as though ‘dict’ is not ordered, at least until a Python version is released with a clear statement that ordering can be relied upon. -- \ “Always do right. This will gratify some people, and astonish | `\the rest.” —Mark Twain | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Gephi development references
Hey there Pythoners, Hope you guys are all well. I am actually very interested in learning the gephi, a platform which is capable of easily developing a variety of awesome graphs. Dose anyone give me some code samples and resources which relates the gephi? Appreciated for reading this! T -- https://mail.python.org/mailman/listinfo/python-list
Re: Microsoft now ships Python with SQL Server
On Sat, Apr 22, 2017 at 5:05 AM, Steve D'Aprano wrote: > https://blogs.technet.microsoft.com/dataplatforminsider/2017/04/ > 19/python-in-sql-server-2017-enhanced-in-database-machine-learning/ > > Quote: > > We are excited to share the preview release of in-database analytics and > machine learning with Python in SQL Server. Python is one of the most > popular languages for data science and has a rich ecosystem of powerful > libraries. > > Starting with the CTP 2.0 release of SQL Server 2017, you can now bring > Python-based intelligence to your data in SQL Server. > > The addition of Python builds on the foundation laid for R Services in SQL > Server 2016 and extends that mechanism to include Python support for > in-database analytics and machine learning. We are renaming R Services to > Machine Learning Services, and R and Python are two options under this > feature. > > /quote > > > -- > Steve > “Cheer up,” they said, “things could be worse.” So I cheered up, and sure > enough, things got worse. > > -- > https://mail.python.org/mailman/listinfo/python-list > Does this mean Python is now Enterprise™? Nah, in all seriousness though; this is good new I think. I'm all for Python becoming even more wide spread. Although I've never used MS SQL, I'm glad people who do use it for work now have an easy to understand language to perform analytics with. It's also great news that they are defaulting to Python 3.5. -- https://mail.python.org/mailman/listinfo/python-list
Re: Turtle window not closing
Thank you for your response. I apologize for that, this is my first time posting so I wasn't sure how to copy my code! I figured out that using the clear() method works for clearing the turtle window after drawing the game board, but now I am trying to figure out how to make the program wait a few seconds or wait for the user to press a key before clearing the turtle window (not closing the window, just clearing it). Is there any way to do this? def draw_board(): t = turtle.Turtle() t.speed(0) t.ht() t.up() t.goto(-100, -100) t.down() for i in range(7, -1, -1): for j in range(0, 8): if free_squares[i][j] == ".": if j != 7: t.fillcolor("green") t.pencolor("black") t.begin_fill() for k in range(4): t.forward(50) t.left(90) t.end_fill() t.forward(50) if j == 7: t.fillcolor("green") t.pencolor("black") t.begin_fill() for k in range(4): t.forward(50) t.left(90) t.end_fill() t.right(270) t.forward(50) t.left(90) t.forward(350) t.right(180) else: if j != 7: for l in range(4): t.forward(50) t.left(90) t.forward(50) if j == 7: for l in range(4): t.forward(50) t.left(90) t.end_fill() t.right(270) t.forward(50) t.left(90) t.forward(350) t.right(180) wn.clear() I appreciate your help. Thanks, Harshi On Saturday, April 22, 2017 3:56 AM, Peter Otten <__pete...@web.de> wrote: Harshika Varadhan via Python-list wrote: > I am creating a game where the user inputs a coordinate to place their > piece on a chess board. My code then draws the chess board with a turtle > and fills in the squares in with green where the user can place their next > piece. After the user inputs their first coordinate, the turtle draws the > board, but then the window doesn't close and the program ends up crashing. It probably raises an exception and prints a traceback. That "traceback" contains the location and a description of the error Python encountered in your script and is therefore valuable information that can help you fix your code. If you get a traceback always include it into your mail (use cut-and- paste). > Is there any way to solve this problem?I appreciate your help. My function > for drawing the chess board: def draw_board(): t = turtle.Turtle() > t.speed(0) t.ht() t.up() t.goto(-100, -100) t.down() for i in > range(0, 8): for j in range(0, 8): if free_squares[i][j] > == ".": if j != 7: t.fillcolor("green") > t.pencolor("black") t.begin_fill() > for k in range(4): t.forward(50) > t.left(90) t.end_fill() > t.forward(50) if j == 7: > t.fillcolor("green") t.pencolor("black") > t.begin_fill() for k in range(4): > t.forward(50) t.left(90) > t.end_fill() t.right(270) > t.forward(50) t.left(90) > t.forward(350) t.right(180) turtle.bye() Thank you, > Harshi That's pretty unreadable. Please remember to post plain text with line- wrapping turned off next time. > the program ends up crashing. If I were to guess: Did you define the `free_squares` list of lists properly? > but then the window doesn't close Are you running your script from within IDLE? Try starting it from the command line instead. Like turtle IDLE itself is a program written in tkinter, and the separation between editer and user code is not always perfect. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
From: eryk sun Sent: Saturday, April 22, 2017 7:59 AM To: Python Main Cc: Albert-Jan Roskam Subject: Re: OrderedDict with kwds On Fri, Apr 21, 2017 at 6:08 PM, Albert-Jan Roskam wrote: > Would the insertion order be preserved if the last line were to be > replaced with: > > if kwds: > for k, v in kwds.items(): > self[k] = v > if args: > self.__update(*args) # no **kwds! The basic problem is that kwds is a regular, unordered dict: def f(**kwds): print(type(kwds)) >>> f() > Hi Eryk, Yes, I realized this later that evening (probably thanks to can of cold beer :-)). But there is hope: https://www.python.org/dev/peps/pep-0468/ . Do you know if there is/will be a "from __future__" to backport that behavior? We're using Python 3.5 now. Thank you! Albert-Jan -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
On Sat, Apr 22, 2017 at 10:41 PM, Ben Finney wrote: > INADA Naoki writes: > >> From Python 3.6, keyword arguments are ordered. So the docstring is >> outdated. > > (Thank you, Inada-san, for the implementation!) > > The announcement of the change specifies that we should not rely on > ordered ‘dict’: > > The order-preserving aspect of this new implementation is considered > an implementation detail and should not be relied upon […]. > > > https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation> > > So, I would recommend continuing to code as though ‘dict’ is not > ordered, at least until a Python version is released with a clear > statement that ordering can be relied upon. See https://www.python.org/downloads/release/python-360/ > PEP 468 Preserving Keyword Argument Order While dict's order is implementation detail, keyword is ordered by language spec. You can rely on it on Python 3.6+. -- https://mail.python.org/mailman/listinfo/python-list
Re: textwrap.fill algorithm? (Difference with vim)
On 2017-04-22, 01:01 GMT, Gregory Ewing wrote: > I don't know what vim is doing, but if you tell Python you > want lines no longer than 65 characters, it takes you at > your word. Oh, I’ve got it. textwrap.fill() (only in Python 2.*?) completely sucks with bytes, because of course it counts every byte as separate character for purpose of counting. All the text must be converted into unicode. It would be probably nice, if the textwrap documentation mentioned it. Best, Matěj -- https://matej.ceplovi.cz/blog/, Jabber: mc...@ceplovi.cz GPG Finger: 3C76 A027 CA45 AD70 98B5 BC1D 7920 5802 880B C9D8 Of course I'm respectable. I'm old. Politicians, ugly buildings, and whores all get respectable if they last long enough. --John Huston in "Chinatown." -- https://mail.python.org/mailman/listinfo/python-list
Re: Bigotry (you win, I give up)
On 04/22/2017 05:17 AM, Rustom Mody wrote: > On Friday, April 21, 2017 at 2:38:08 PM UTC+5:30, Antoon Pardon wrote: >> Op 20-04-17 om 17:25 schreef Rustom Mody: >>> But more importantly thank you for your polite and consistent pointing out >>> to >>> Ben Finney that his religion-bashing signature lines [many of them] and his >>> claims to wish this list be welcoming are way out of sync. >> >> I don't know. I think a concept like welcoming is too complex, to draw such >> simple conclusions. First of all we have to make a choice about the public we >> want to be welcoming to. I'm rather confident we can agree we don't want to >> be welcoming to bigots on this list. >> >> Then feeling welcome is not a boolean, people can feel welcome to a different >> degree and there are many factors at work. If people tend to react in a >> friendly >> manner to there co-participants, people generally should feel welcome. A >> statment >> in a signature that isn't addressing anyone personnaly may give rise to some >> irritation but shouldn't make this list feel unwelcome to someone. > > Generally agree > [though I wonder how you will decide what constitutes a 'bigot'. Look at the > suggestion in the very subject of these threads] As the author of that subject, I'm not sure what point you are trying to make but let me point out that "bigot" does NOT appear in the subject line. I distinguish between "bigotry", an expression of intolerance and prejudice and "bigot", a person who repeatedly and knowingly makes bigoted statements. It also seems to me that "bigot", like "racist", has very little intellectual value having been degraded by use to little more than a stronger more emotive form of "asshole" or "dickhead". >> Do you think critising any idea in one's signature is enough to conclude that >> this person doesn't wish this list to be welcoming? I have to agree Antoon here. I think there is a distinction between a signature that expresses an opinion (even an offensive one to some) and the use of prejudice and bigotry directly in a message and used to attack a person or idea rather than a reasoned refutation of the idea itself. After all, listening to and understanding (though not necessarily) agreeing with) opinions that differ from our own is surely something not to be discouraged? c.l.p: Me: I think python strings should be mutable. Someome: That's stupid. You sound like a typical Rurplandian who we know have IQ scores 15 points lower than us. [It's true that we have lower IQ scores.] vs. a sig: -- Because of the stupidity of its people, Rurplandia should not be admitted to the UN. I would find the former offensive and objectionable, the latter offensive but acceptable. That being said, there are certainly sigs that are offensive enough to community standards as to be unacceptable. But the bar for sigs should be much higher than for bigotry directed towards a person in a discussion. And the point of my first post remains: whatever that bar is should be applied evenhandedly, with regard to both the poster and to the politics expressed. -- https://mail.python.org/mailman/listinfo/python-list
Re: textwrap.fill algorithm? (Difference with vim)
Matěj Cepl wrote: > On 2017-04-22, 01:01 GMT, Gregory Ewing wrote: >> I don't know what vim is doing, but if you tell Python you >> want lines no longer than 65 characters, it takes you at >> your word. > > Oh, I’ve got it. textwrap.fill() (only in Python 2.*?) completely > sucks with bytes, because of course it counts every byte as > separate character for purpose of counting. All the text must be > converted into unicode. It would be probably nice, if the > textwrap documentation mentioned it. Yes, the documentation should warn about the limitations of textwrap's notion of width -- but still, the line you complained about 10203040506070 123456789+123456789+123456789+123456789+123456789+123456789+123456789+12 It is necessary to issue this caution, for the popular mind has grown so contains only ascii, so whether you count bytes or characters -- it's always 72, not 65. -- https://mail.python.org/mailman/listinfo/python-list
Re: Metaclass conundrum - binding value from an outer scope
> Another round, this time with a metaclass. As you have found partial() does > not work as a method because it's not a descriptor (i. e. no __get__() > method). Instead you can try a closure: > > def make_method(a): > underlying = getattr(SomeOtherClass, a) > @functools.wraps(underlying) > def _meth(self, *args, **kw): > return underlying(self._instance, *args, **kw) > return _meth > > class SomeMeta(type): > def __new__(cls, name, parents, dct): > for a in dir(SomeOtherClass): > if a[0] == "_": continue > dct[a] = make_method(a) > return super(SomeMeta, cls).__new__(cls, name, parents, dct) Dang, Peter... That looks like it will do exactly what I need. Here's help on SomeOtherClass with its one method: class SomeOtherClass(__builtin__.object) | Methods defined here: | | meth1(self) | meth1 doc ... And, here's SomeClass (__metaclass__ = SomeMeta), which defines meth2, but steals meth1 from SomeOtherClass: class SomeClass(__builtin__.object) | Methods defined here: | | meth1(self, *args, **kw) | meth1 doc | | meth2(self) | meth2 doc ... With a bit of introspection in make_method (or an extension of functools.wraps), I can probably make SomeClass.meth1 have the same signature as SomeOtherClass.meth1. Thx, Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: Rawest raw string literals
On 20 April 2017 at 18:40, Grant Edwards wrote: > On 2017-04-20, Mikhail V wrote: >> On 20 April 2017 at 17:59, Grant Edwards wrote: >>> On 2017-04-20, Mikhail V wrote: Quite often I need raw string literals for concatenating console commands. I want to input them exactly as they are in python sources. There is r"" string, but it is obviously not enough because e.g. this: s = r"ffmpeg -i "\\server-01\D\SER_Bigl.mpg" " >>> >>>s = r'ffmpeg -i "\\server-01\D\SER_Bigl.mpg" ' >>> >>> Does that do what you want? >> >> Yes but it still needs to watch out if there is no ' inside or vice >> versa with " characters if use r"". I would like a universal >> solution. > > IOW, you want something that just reads your mind. > > How can there exist a "universal solution" even in theory? > > There has to be some sort of "end of literal" terminator character > sequence. That means there has to be some sort of escaping mechanism > when that "end of literal" sequence appears in the literal itself. > In *theory* one can define what characters can be part of the raw string. In Python e.g. the newline character cannot be part of the r"" string (unless a line ends with \): k = r"abc def" gives an error: k = r"abc ^ SyntaxError: EOL while scanning string literal So one could define a rule, that a raw string *must* be terminated by the sequence quote + newline. In theory. Mikhail -- https://mail.python.org/mailman/listinfo/python-list
Re: Metaclass conundrum - binding value from an outer scope
Skip Montanaro wrote: >> Another round, this time with a metaclass. As you have found partial() >> does not work as a method because it's not a descriptor (i. e. no >> __get__() method). Instead you can try a closure: >> >> def make_method(a): >> underlying = getattr(SomeOtherClass, a) >> @functools.wraps(underlying) >> def _meth(self, *args, **kw): >> return underlying(self._instance, *args, **kw) >> return _meth >> >> class SomeMeta(type): >> def __new__(cls, name, parents, dct): >> for a in dir(SomeOtherClass): >> if a[0] == "_": continue >> dct[a] = make_method(a) >> return super(SomeMeta, cls).__new__(cls, name, parents, dct) > > Dang, Peter... That looks like it will do exactly what I need. Here's > help on SomeOtherClass with its one method: > > class SomeOtherClass(__builtin__.object) > | Methods defined here: > | > | meth1(self) > | meth1 doc > ... > > And, here's SomeClass (__metaclass__ = SomeMeta), which defines meth2, > but steals meth1 from SomeOtherClass: > > class SomeClass(__builtin__.object) > | Methods defined here: > | > | meth1(self, *args, **kw) > | meth1 doc > | > | meth2(self) > | meth2 doc > ... > > With a bit of introspection in make_method (or an extension of > functools.wraps), I can probably make SomeClass.meth1 have the same > signature as SomeOtherClass.meth1. > > Thx, > > Skip In Python 3 you should see the correct signature, for Python 2 I think this addressed by Michele Simionato's https://pypi.python.org/pypi/decorator http://pythonhosted.org/decorator/documentation.html#id8 module. -- https://mail.python.org/mailman/listinfo/python-list
Re: Rawest raw string literals
On Sun, Apr 23, 2017 at 7:13 AM, Mikhail V wrote: > So one could define a rule, that a raw string *must* > be terminated by the sequence quote + newline. > In theory. Then how would you pass one as a function parameter? func(r"" ) Ugh. Ugly. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: How to get Buttons to work
(sorry for top-posting). UpdateRecords and the other functions need to be nested so they fall under your class. Right now they are functions, not methods. AJ From: Python-list on behalf of horgan.ant...@gmail.com Sent: Saturday, April 22, 2017 12:45:09 PM To: python-list@python.org Subject: How to get Buttons to work I am busy learning Python and I want to make a simple program that connects to a database to locate the information of Doctors. Now the as far as I can see everything works fine, database connects, info gets displayed, but the buttons don't want to work. Please see code and error below. Any help will be greatly appreciated. Error: Traceback (most recent call last): File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 57, in myapp = MyForm() File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 29, in __init__ QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' ), self.UpdateRecords) AttributeError: 'MyForm' object has no attribute 'UpdateRecords' >>> Code: #CallDoctorLocator import sys from DoctorLocator import * from PyQt4 import QtSql, QtGui #Create Connection to the Database def createConnection(): db = QtSql.QSqlDatabase.addDatabase('QMYSQL') db.setHostName('localhost') db.setDatabaseName('healthcare') db.setUserName('root') db.setPassword('3364834') db.open() print (db.lastError().text()) return True class MyForm(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.model = QtSql.QSqlTableModel(self) self.model.setTable("doctors") self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.model.select() self.ui.tableView.setModel(self.model) QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' ), self.UpdateRecords) QtCore.QObject.connect(self.ui.buttonCancel, QtCore.SIGNAL('clicked()' ), self.CancelChanges) QtCore.QObject.connect(self.ui.buttonAdd, QtCore.SIGNAL('clicked()' ), self.AddRecord) QtCore.QObject.connect(self.ui.buttonDelete, QtCore.SIGNAL('clicked()' ), self.DeleteRecord) QtCore.QObject.connect(self.ui.buttonSearch, QtCore.SIGNAL('clicked()' ), self.SearchRecords) def UpdateRecords(self): self.model.AddRecord() def CancelChanges(self): self.model.revertAll() def UpdateRecords (self): self.model.insertRow(self.ui.tableView.currentIndex().row()) def DeleteRecords(self): self.model.removeRow(self.ui.tableView.currentIndex().row()) self.model.AddRecord() def SearchRecords(self): self.model.setFilter("Name like '" + self.ui.Name.text()+"%'") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) if not createConnection(): sys.exit(1) myapp = MyForm() myapp.show() sys.exit(app.exec_()) -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Rawest raw string literals
On 2017-04-22 23:13, Mikhail V wrote: > k = r"abc > def" > > gives an error: > > k = r"abc > ^ > SyntaxError: EOL while scanning string literal > > So one could define a rule, that a raw string *must* > be terminated by the sequence quote + newline. > In theory. Though one can do k = r"""abc def ghi jkl mno pqrs \tuv wxyz """ which keeps the "\" while allowing multi-line strings. -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: textwrap.fill algorithm? (Difference with vim)
On 2017-04-22, 18:33 GMT, Peter Otten wrote: > Yes, the documentation should warn about the limitations of > textwrap's notion of width -- but still, the line you > complained about Perhaps, I have screwed up somewhere, but I am glad we were able to figure it out. Thank you for your patience, Matěj -- https://matej.ceplovi.cz/blog/, Jabber: mc...@ceplovi.cz GPG Finger: 3C76 A027 CA45 AD70 98B5 BC1D 7920 5802 880B C9D8 Of course I'm respectable. I'm old. Politicians, ugly buildings, and whores all get respectable if they last long enough. --John Huston in "Chinatown." -- https://mail.python.org/mailman/listinfo/python-list
String escaping utility for Python (was: Rawest raw string literals)
On 20 April 2017 at 23:54, MRAB wrote: > On 2017-04-20 22:03, Mikhail V wrote: >> >> On 20 April 2017 at 22:43, Random832 wrote: >>> [snip] >>> >>> The best solution I can think of is to have a text editor designed to >>> parse a string literal, spawn a nested editor with the unescaped >>> contents of that string literal, and then re-escape it back to place in >>> the code. If we had that, then we wouldn't even need raw strings. >> >> >> Yes exactly, it would be cool to have such a satellite app >> which can escape and unescape strings according to rules. >> And which can also convert unicode literals to their ascii >> analogues and back on the fly, this would very useful >> for programming. >> Probably it is a good idea to even include such thing >> in Python package. So it would be a small standalone app >> running parallel with text editor making it to copy paste strings. >> > I'm sure it's possible in, say, Emacs. > > The editor that I use (EditPad Pro) can call external tools, so I could: > > 1. Select the string literal (easy when it is syntax-aware, so I can select > all of the literal with 2 keypresses). > > 2. Call the external tool (1 keypress), to open, say, a simple tkinter app. > > 3. Edit the unescaped text (unescape with ast.literal_eval, re-escape with > 'ascii'). > > 4. Close the external tool, and the selection is replaced. I have done a quick google search and could not find such utility for Python. I am very interested in having such utility. And I think it would be fair that such utility should be made by the Python team so that all syntax nuances will be correctly implemented. The purpose is simple: reduce manual work to escape special characters in string literals (and escape non-ASCII characters). Simple usage scenario: - I have a long command-line string in some text editor. - Copy this string and paste into the utility edit box - In the second edit box same string with escaped characters appears (i.e tab becomes \t, etc) - Further, if I edit the text in the second edit box, an unescaped string appears in the first box. Possible toggle options, e.g. : - 'asciify' non-ascii characters It could be not only useful to eliminate boilerplate typing, but also a great way to learn string rules for Python learners. PS: Also I remember now about the python-ideas thread on entering unicode characters with decimals instead of hex values. It was met somewhat negatively but then it turned out that in recent Python version it can be done with f-strings. E.g. a string : s="абв" one can write as: s = f"{1072:c}{1073:c}{1074:c}" instead of traditional hex: "\u0430\u0431\u0432" It was told however this is not normal usage. Still I find it very helpful, so if this is correct syntax, I'd personally find such a conversion option also very useful. Mikhail -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On Sun, Apr 23, 2017 at 8:30 AM, Mikhail V wrote: > The purpose is simple: reduce manual work to escape special > characters in string literals (and escape non-ASCII characters). > > Simple usage scenario: > - I have a long command-line string in some text editor. > - Copy this string and paste into the utility edit box > - In the second edit box same string with escaped characters > appears (i.e tab becomes \t, etc) > - Further, if I edit the text in the second edit box, > an unescaped string appears in the first box. Easy. >>> input() This string has "quotes" of 'various' «styles», and \backslashes\ too. 'This string has "quotes" of \'various\' «styles», and \\backslashes\\ too.' The repr of a string does pretty much everything you want. If you want a nice GUI, you can easily put one together that uses repr() to escape and ast.literal_eval() to unescape. > PS: > Also I remember now about the python-ideas thread > on entering unicode characters with decimals instead of > hex values. It was met somewhat negatively but then it turned out > that in recent Python version it can be done with f-strings. > E.g. a string : > > s="абв" > one can write as: > s = f"{1072:c}{1073:c}{1074:c}" > instead of traditional hex: > "\u0430\u0431\u0432" > > It was told however this is not normal usage. > Still I find it very helpful, so if this is correct syntax, I'd > personally find such a conversion option also very useful. Most of the world finds the hex form MUCH more logical, since Unicode is built around 16s and 256s and such. Please don't proliferate more messes - currently, the only place I can think of where decimal is supported is HTML character entities, and hex is equally supported there. Of course, the best way to represent most non-ASCII characters is as themselves - s="абв" from your example. The main exception is combining characters and related incomplete forms, such as this table of diacritical marks more-or-less lifted from an app of mine: { "\\`":"\u0300","\\'":"\u0301","\\^":"\u0302","\\~":"\u0303", "\\-":"\u0304","\\@":"\u0306","\\.":"\u0307","\\\"":"\u0308", "\\o":"\u030A","\\=":"\u030B","\\v":"\u030C","\\<":"\u0326", "\\,":"\u0327","\\k":"\u0328", } All of them are in the 03xx range. Much easier than pointing out that they're in the range 768 to 879. Please stick to hex. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On 23 April 2017 at 00:48, Chris Angelico wrote: > On Sun, Apr 23, 2017 at 8:30 AM, Mikhail V wrote: >> The purpose is simple: reduce manual work to escape special >> characters in string literals (and escape non-ASCII characters). >> >> Simple usage scenario: >> - I have a long command-line string in some text editor. >> - Copy this string and paste into the utility edit box >> - In the second edit box same string with escaped characters >> appears (i.e tab becomes \t, etc) >> - Further, if I edit the text in the second edit box, >> an unescaped string appears in the first box. > > Easy. > input() > This string has "quotes" of 'various' «styles», and \backslashes\ too. > 'This string has "quotes" of \'various\' «styles», and \\backslashes\\ too.' > > The repr of a string does pretty much everything you want. If you want > a nice GUI, you can easily put one together that uses repr() to escape > and ast.literal_eval() to unescape. I am sorry, could you elaborate what have you shown here? So in Python console I can become escaped string, but what commands do you use? I never use Python console actually :/ And yes the idea is to have a nice GUI. And the idea is exactly opposite to "everyone let's roll an own tool". Obviously I can spend day or two and create such a tool, e.g. with PyQt. But since the task is very common and quite unambiguos I think it is a good reason for a standard official tool. > >> PS: >> Also I remember now about the python-ideas thread >> on entering unicode characters with decimals instead of >> hex values. It was met somewhat negatively but then it turned out >> that in recent Python version it can be done with f-strings. >> E.g. a string : >> >> s="абв" >> one can write as: >> s = f"{1072:c}{1073:c}{1074:c}" >> instead of traditional hex: >> "\u0430\u0431\u0432" >> >> It was told however this is not normal usage. >> Still I find it very helpful, so if this is correct syntax, I'd >> personally find such a conversion option also very useful. > > Most of the world finds the hex form MUCH more logical, since Unicode > is built around 16s and 256s and such. Please don't proliferate more > messes - currently, the only place I can think of where decimal is > supported is HTML character entities, and hex is equally supported > there. > > Of course, the best way to represent most non-ASCII characters is as > themselves - s="абв" from your example. The main exception is > combining characters and related incomplete forms, such as this table > of diacritical marks more-or-less lifted from an app of mine: > > { > "\\`":"\u0300","\\'":"\u0301","\\^":"\u0302","\\~":"\u0303", > "\\-":"\u0304","\\@":"\u0306","\\.":"\u0307","\\\"":"\u0308", > "\\o":"\u030A","\\=":"\u030B","\\v":"\u030C","\\<":"\u0326", > "\\,":"\u0327","\\k":"\u0328", > } > > All of them are in the 03xx range. Much easier than pointing out that > they're in the range 768 to 879. Please stick to hex. I don't insist on decimals, I want to use decimals for my own pleasure in own projects, may I? And don't worry in my whole life I will not produce so many software that will significantly increase the 'messes'. (Anyway I've got used already to decimals somehow, ord(char), etc., so for me it's too late for the ugly hex) Mikhail -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On Sun, Apr 23, 2017 at 10:19 AM, Mikhail V wrote: > On 23 April 2017 at 00:48, Chris Angelico wrote: >> On Sun, Apr 23, 2017 at 8:30 AM, Mikhail V wrote: >>> The purpose is simple: reduce manual work to escape special >>> characters in string literals (and escape non-ASCII characters). >>> >>> Simple usage scenario: >>> - I have a long command-line string in some text editor. >>> - Copy this string and paste into the utility edit box >>> - In the second edit box same string with escaped characters >>> appears (i.e tab becomes \t, etc) >>> - Further, if I edit the text in the second edit box, >>> an unescaped string appears in the first box. >> >> Easy. >> > input() >> This string has "quotes" of 'various' «styles», and \backslashes\ too. >> 'This string has "quotes" of \'various\' «styles», and \\backslashes\\ too.' >> >> The repr of a string does pretty much everything you want. If you want >> a nice GUI, you can easily put one together that uses repr() to escape >> and ast.literal_eval() to unescape. > > I am sorry, could you elaborate what have you shown here? > So in Python console I can become escaped string, but what > commands do you use? I never use Python console actually :/ You type "input()" at the Python console, then type the string you want. It will be echoed back in representation form, with everything correctly escaped. > And yes the idea is to have a nice GUI. And the idea is exactly opposite > to "everyone let's roll an own tool". Obviously I can spend day > or two and create such a tool, e.g. with PyQt. > But since the task is very common and quite unambiguos I think it is > a good reason for a standard official tool. Or you could spend two seconds firing up the Python REPL, which has all the tools you need right there :) >>> PS: >>> Also I remember now about the python-ideas thread >>> on entering unicode characters with decimals instead of >>> hex values. It was met somewhat negatively but then it turned out >>> that in recent Python version it can be done with f-strings. >>> E.g. a string : >>> >>> s="абв" >>> one can write as: >>> s = f"{1072:c}{1073:c}{1074:c}" >>> instead of traditional hex: >>> "\u0430\u0431\u0432" >>> >>> It was told however this is not normal usage. >>> Still I find it very helpful, so if this is correct syntax, I'd >>> personally find such a conversion option also very useful. >> >> Most of the world finds the hex form MUCH more logical, since Unicode >> is built around 16s and 256s and such. Please don't proliferate more >> messes - currently, the only place I can think of where decimal is >> supported is HTML character entities, and hex is equally supported >> there. >> >> Of course, the best way to represent most non-ASCII characters is as >> themselves - s="абв" from your example. The main exception is >> combining characters and related incomplete forms, such as this table >> of diacritical marks more-or-less lifted from an app of mine: >> >> { >> "\\`":"\u0300","\\'":"\u0301","\\^":"\u0302","\\~":"\u0303", >> "\\-":"\u0304","\\@":"\u0306","\\.":"\u0307","\\\"":"\u0308", >> "\\o":"\u030A","\\=":"\u030B","\\v":"\u030C","\\<":"\u0326", >> "\\,":"\u0327","\\k":"\u0328", >> } >> >> All of them are in the 03xx range. Much easier than pointing out that >> they're in the range 768 to 879. Please stick to hex. > > I don't insist on decimals, I want to use decimals for my own pleasure > in own projects, may I? > And don't worry in my whole life I will not produce so many software > that will significantly increase the 'messes'. > (Anyway I've got used already to decimals somehow, ord(char), etc., > so for me it's too late for the ugly hex) Will your projects ever be shared with anyone else? If so, please use the standard. In your own projects, you're welcome to shoot yourself in the foot, but I'm not going to help you. I'm going to encourage hex for Unicode. It's not too late for you to adjust your mind to the standard. And I strongly recommend it. There are good reasons for hex, and the sooner you change, the easier it'll be. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On 23 April 2017 at 02:33, Chris Angelico wrote: > On Sun, Apr 23, 2017 at 10:19 AM, Mikhail V wrote: >> On 23 April 2017 at 00:48, Chris Angelico wrote: >>> On Sun, Apr 23, 2017 at 8:30 AM, Mikhail V wrote: The purpose is simple: reduce manual work to escape special characters in string literals (and escape non-ASCII characters). Simple usage scenario: - I have a long command-line string in some text editor. - Copy this string and paste into the utility edit box - In the second edit box same string with escaped characters appears (i.e tab becomes \t, etc) - Further, if I edit the text in the second edit box, an unescaped string appears in the first box. >>> >>> Easy. >>> >> input() >>> This string has "quotes" of 'various' «styles», and \backslashes\ too. >>> 'This string has "quotes" of \'various\' «styles», and \\backslashes\\ too.' >>> >>> The repr of a string does pretty much everything you want. If you want >>> a nice GUI, you can easily put one together that uses repr() to escape >>> and ast.literal_eval() to unescape. >> >> I am sorry, could you elaborate what have you shown here? >> So in Python console I can become escaped string, but what >> commands do you use? I never use Python console actually :/ > > You type "input()" at the Python console, then type the string you > want. It will be echoed back in representation form, with everything > correctly escaped. > >> And yes the idea is to have a nice GUI. And the idea is exactly opposite >> to "everyone let's roll an own tool". Obviously I can spend day >> or two and create such a tool, e.g. with PyQt. >> But since the task is very common and quite unambiguos I think it is >> a good reason for a standard official tool. > > Or you could spend two seconds firing up the Python REPL, which has > all the tools you need right there :) > Don't know, all I see is "SyntaxError: invalid syntax" if I paste there some text. Try to paste e.g. this: "ffmpeg -i "D:\VIDEO\exp\intro.mp4" -vf "crop=1280:720:0:40, scale=640:360" -pix_fmt yuv420p "D:\ART\0MASTER_UMST\yt_pico.mp4"" But are you joking, right? Even if it worked, how can this be convinient, e.g. in console one cannot even select and copy paste easily. Probably one can make a python script which takes clipboard contents then place the conversion result back to clipboard. Like: - copy some text to clipboard - run the script, which replace the clipboard contents with result - paste text I haven't tried that, but even this would be very inconvenient and limited in comparison to a GUI utility. Mikhail -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On Sun, Apr 23, 2017 at 12:06 PM, Mikhail V wrote: > Don't know, all I see is "SyntaxError: invalid syntax" if I paste > there some text. > Try to paste e.g. this: > "ffmpeg -i "D:\VIDEO\exp\intro.mp4" -vf "crop=1280:720:0:40, > scale=640:360" -pix_fmt yuv420p "D:\ART\0MASTER_UMST\yt_pico.mp4"" Oh. I should have said that my example was for Python 3. If you're using Python 2, use raw_input() instead. Or just switch to Python 3. > But are you joking, right? Even if it worked, how can this be convinient, > e.g. in console one cannot even select and copy paste easily. Get a better console. Even in Windows, the default console is fully capable of copying and pasting text, but you can do better than the default. On every Linux desktop I've used, the console is beautifully easy to use (GNOME, LXDE, Mate, Xfce, and probably a few others as well). > Probably one can make a python script which takes clipboard contents > then place the conversion result back to clipboard. > Like: > - copy some text to clipboard > - run the script, which replace the clipboard contents with result > - paste text > > I haven't tried that, but even this would be very inconvenient and > limited in comparison > to a GUI utility. You can do that too if you want to. I don't know how you'd do that with tkinter, but it ought to be possible, and then you wouldn't need any third party libraries. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On Sun, Apr 23, 2017 at 2:06 AM, Mikhail V wrote: > > But are you joking, right? Even if it worked, how can this be convinient, > e.g. in console one cannot even select and copy paste easily. The X terminals that I've used make it easy to copy text to the clipboard. For Windows, it's a pain prior to Windows 10 since the legacy console only does rectangular selection. The Windows 10 console does line-wrapped selection. -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On Sun, Apr 23, 2017 at 12:30 PM, eryk sun wrote: > The X terminals that I've used make it easy to copy text to the > clipboard. For Windows, it's a pain prior to Windows 10 since the > legacy console only does rectangular selection. The Windows 10 console > does line-wrapped selection. This is true, but if you're using Python for simple text manipulation as I suggest here, rectangular selection is usually fine. At worst, you have to rejoin the lines after you paste. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: String escaping utility for Python (was: Rawest raw string literals)
On 2017-04-22 23:30, Mikhail V wrote: On 20 April 2017 at 23:54, MRAB wrote: > On 2017-04-20 22:03, Mikhail V wrote: >> >> On 20 April 2017 at 22:43, Random832 wrote: >>> [snip] >>> >>> The best solution I can think of is to have a text editor designed to >>> parse a string literal, spawn a nested editor with the unescaped >>> contents of that string literal, and then re-escape it back to place in >>> the code. If we had that, then we wouldn't even need raw strings. >> >> >> Yes exactly, it would be cool to have such a satellite app >> which can escape and unescape strings according to rules. >> And which can also convert unicode literals to their ascii >> analogues and back on the fly, this would very useful >> for programming. >> Probably it is a good idea to even include such thing >> in Python package. So it would be a small standalone app >> running parallel with text editor making it to copy paste strings. >> > I'm sure it's possible in, say, Emacs. > > The editor that I use (EditPad Pro) can call external tools, so I could: > > 1. Select the string literal (easy when it is syntax-aware, so I can select > all of the literal with 2 keypresses). > > 2. Call the external tool (1 keypress), to open, say, a simple tkinter app. > > 3. Edit the unescaped text (unescape with ast.literal_eval, re-escape with > 'ascii'). > > 4. Close the external tool, and the selection is replaced. I have done a quick google search and could not find such utility for Python. I am very interested in having such utility. And I think it would be fair that such utility should be made by the Python team so that all syntax nuances will be correctly implemented. The purpose is simple: reduce manual work to escape special characters in string literals (and escape non-ASCII characters). Simple usage scenario: - I have a long command-line string in some text editor. - Copy this string and paste into the utility edit box - In the second edit box same string with escaped characters appears (i.e tab becomes \t, etc) - Further, if I edit the text in the second edit box, an unescaped string appears in the first box. Possible toggle options, e.g. : - 'asciify' non-ascii characters It could be not only useful to eliminate boilerplate typing, but also a great way to learn string rules for Python learners. Here's a very simple tkinter GUI app. It only goes one way (plain to escaped (asciified)), but it shows what's possible with very little code. #! python3.6 # -*- coding: utf-8 -*- import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title('Escaper') tk.Label(self, text='Plain string').pack() self.plain_box = tk.Text(self) self.plain_box.pack() self.plain_box.focus() tk.Label(self, text='Escaped string').pack() self.escaped_box = tk.Text(self) self.escaped_box.pack() self.after(100, self.on_tick) def on_tick(self): plain_string = self.plain_box.get('1.0', 'end')[ : -1] escaped_string = ascii(plain_string) self.escaped_box.delete('1.0', 'end') self.escaped_box.insert('1.0', escaped_string) self.after(100, self.on_tick) App().mainloop() -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
INADA Naoki writes: > On Sat, Apr 22, 2017 at 10:41 PM, Ben Finney > wrote: > > So, I would recommend continuing to code as though ‘dict’ is not > > ordered, at least until a Python version is released with a clear > > statement that ordering can be relied upon. > > While dict's order is implementation detail, keyword is ordered by > language spec. Ah, I had missed that distinction. Thank you for the explanation. Yes, Python 3.6 keyword arguments now preserve the order from the function call. Great! -- \ “If you always want the latest and greatest, then you have to | `\ buy a new iPod at least once a year.” —Steve Jobs, MSNBC | _o__) interview 2006-05-25 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: OrderedDict with kwds
Albert-Jan Roskam writes: > The basic problem is that kwds is a regular, unordered dict […] (Albert, you are probably aware that the above passage is not what you wrote. But your message shows it indistinguishable from your other text. Please teach your email client to compose quoted material using https://en.wikipedia.org/wiki/Posting_style#Quoted_line_prefix> the conventional line prefix of “> ” — and, if your email client can't be taught to do that in plain text, please choose a better email client.) > Yes, I realized this later that evening (probably thanks to can of > cold beer :-)). But there is hope: > https://www.python.org/dev/peps/pep-0468/ . Do you know if there > is/will be a "from __future__" to backport that behavior? We're using > Python 3.5 now. The ‘__future__’ features are language features, and like other features they do not get added retro-actively to an already released Python version. So, Python 3.5 has a set of ‘__future__’ features that are the only ones that will ever be in Python 3.5. When a feature is added to ‘__future__’ it is to introduce a backward-incompatible feature gradually, and like any feature is always added as part of the development of Python versions. So, new features in ‘__future__’ will only appear in *not yet released* Python versions. https://docs.python.org/3/library/__future__.html> In short: To get the changed behaviour, you need a newer Python version. -- \ “If you don't want your beliefs to be ridiculed, don't have | `\such ridiculous beliefs.” —Greta Christina, 2011-10-22 | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Turtle window not closing
On 4/22/2017 3:52 AM, Peter Otten wrote: Harshika Varadhan via Python-list wrote: Are you running your script from within IDLE? Try starting it from the command line instead. Like turtle IDLE itself is a program written in tkinter, and the separation between editer and user code is not always perfect. By default (now), IDLE runs user code, which in this case includes the turtle and hence tkinter modules, in a separate process in which tkinter is NOT used by IDLE (except for an error exit message). Making it possible to develop tkinter code with IDLE was a major reason for adding the two process mode. That said, the separation cannot be perfect (only one process can have keyboard focus, for instance), and so in the absence of other ideas, I also sometimes recommend running from a command line. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list