Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On Tue, Jul 30, 2019 at 11:24 AM boB Stepp wrote: > In this trivial example I cannot imagine there is any realistic > difference between the two approaches, but I am trying to generalize > my thoughts for potentially much more expensive calculations, very > large data sets, and what is the likelihood of storage errors > occurring in files. Any thoughts on this? As with many things in programming, it comes down to how much time you want to trade for space. If you have a lot of space and not much time, store the calculated values. If you have a lot of time (or the calculation time is negligible) and not much space, recalculate every time. If you have plenty of both, store it and recalculate it anyway :). Storing the information can also be useful for offline debugging. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble Downloading To MacOS Mojave 10.14.3 released mid 2014
On Wed, Mar 13, 2019 at 7:06 AM Robert Landers wrote: > Hello Tutor, Hi Robert, and welcome! > I am having trouble finding a python 3.7.2 download for my MacOS Mojave > 10.14.3 released mid 2014. If you go to https://www.python.org/downloads/, the large yellow "Download Python ..." button near the top of the page should give you the installer for the latest version of Python. > I would like to use Xcode to learn python. Xcode doesn't really have any support for Python. You may be able to use it to edit Python code, but you'll probably be happier with any number of other editors that do properly support Python, like VS Code, PyCharm, Sublime, or Atom (full disclosure: of those I've only used VS Code and PyCharm, and usually use vim instead). > Is my OS too old? No, in fact I'm pretty sure you have the latest version (for reference, macOS Mojave 10.14.3 was released a month ago on 7Feb2019) :). The Python installer may say 10.9, but that is the minimum required version; anything later than that is supported (including 10.14). Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying Status on the Command Line
On Thu, Nov 8, 2018 at 10:10 AM Steven D'Aprano wrote: > Sorry, I don't understand that. Maybe its too early in the morning for > my brain, but given that you've imported the Python 3 print function > from the __future__ why do you need the customer wrapper? > > from __future__ import print_function > > alone should give you exactly the Python 3 print function, with all its > bells and whistles. > > What have I missed? The `flush` parameter was added in 3.3. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying Status on the Command Line
On Thu, Nov 8, 2018 at 4:12 AM Chip Wachob wrote: > I should have mentioned that I'm working with Python 2, but I think I > can parse my way through these examples. You can use any of the `print` function tricks above in Python 2 with the following boilerplate: from __future__ import print_function import sys _orig_print = print def print(*args, **kwargs): flush = kwargs.pop('flush', False) _orig_print(*args, **kwargs) if flush: file = kwargs.get('file', sys.stdout) file.flush() When you get to upgrade to Python 3, just throw the above code away and things will work just the same :) -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying Status on the Command Line
On Wed, Nov 7, 2018 at 1:17 PM Alan Gauld via Tutor wrote: > In Python 3 there are parameters to print() > > while someProcess(): >time.sleep(1) >print('.', end='', sep='') # no newline and no spaces You'll also want `flush=True` here to avoid having your dots buffered until end-of-line. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SSL Error
On Tue, Jul 31, 2018 at 12:06 PM Alan Gauld via Tutor wrote: > > On 31/07/18 03:52, Saket Mehrotra wrote: > > > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' > > Are you sure you spelled the attribute correctly? > > Have you tried > > > >>> import ssl > >>> dir(ssl) > > Top see what the attribute names look like? > Is PROTOCOL_SSLv23 one of them? Also check `ssl.__file__` and make sure it is the standard library's `ssl.py` (/usr/lib/python3.6/ssl.py or similar) and not a local file of yours named `ssl.py`. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor wrote: > There are lots of options including those suggested elsewhere. > Another involves using get() which makes your function > look like: > > def viceversa(d): > new_d = dict() > for k in d: > for e in d[k]: > new_d[e] = new_d.get(e,[]).append(k) Note that this will set each entry to `None` as returned by `list.append`. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera wrote: > I was looking to substiture the cicle for e in new_d like this: > [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in d[k] ] > but it can't work because 'new_d[e] = []' is missing. Have a look at `dict.setdefault` and play around with it; I think it will help you do what you want. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip stopped working gives error
On Thu, May 3, 2018 at 2:10 PM, Jimwrote: > I have python 3.6 installed in a virtual environment on Mint 18. Today I > wanted to use pip and got this error when I tried to use it. > > (env36) jfb@jims-mint18 ~ $ pip help > Traceback (most recent call last): > File "/home/jfb/EVs/env36/bin/pip", line 7, in > from pip import main > File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", > line 43, in > from pip.utils import get_installed_distributions, get_prog > File > "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", > line 23, in > from pip.locations import ( > File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", > line 9, in > from distutils import sysconfig > ImportError: cannot import name 'sysconfig' > > I searched for sysconfig and found this: > > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py > > The results seem to be the same as when I searched a python 3.5 virtual > environment I have setup. > > It has worked in the past as I have installed pylint and pykeyboard with it. > As I type this I just remembered Mint updated python 3.6 earlier today. > > So now I suspect the update is involved. Has anyone else experienced this > and know how to fix it? First, try a clean venv (python3.6 -m venv venv && ./venv/bin/pip help). If that works, then one of the nice things about virtual environments is that they're easy to recreate, especially if you have a handy list of the packages you want, say in a `requirements.txt` file. Then all you need to do is `python3.6 -m venv --clear /path/to/your/old/venv && /path/to/your/old/venv/bin/pip install -r requirements.txt`. If you don't already have a requirements.txt file, you can create one by listing the names of the packages you want in a file, each on its own line. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sam Kahraman Campus Middle School Advice
Hi Sam, On Thu, Apr 26, 2018 at 3:00 PM, Kahraman, Sam K.wrote: > Hello, > > I am a 8th grade student at Campus Middle School. We have a project on > coding and I need a expert to interview. Currently I'm learning Python and > thought I should ask someone who works their to Interview. To contact me and > ask any questions my email is skahra...@cherrycreekschools.org. Can you give some more details on what exactly you're looking for? This is a fairly unusual request for this mailing list, but I'm sure we can at least point you in the right direction. It might be easiest to just ask your questions here, and you're likely to get more answers than you bargained for :) Regards, Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about tree input
On Mon, Apr 23, 2018 at 11:28 AM, 劉權陞 <01patrick...@gmail.com> wrote: > I still have no idea about how to write the code. Can you make a > demonstration? Something like this: def set(tree, path, key, value): for p in path: tree = tree[p] tree[key] = value -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about tree input
Basically what you want to do here is give Tree a local name (d), loop through T reassigning d to d[k_from_T], and then d[k] = v after the loop. T can be arbitraily long, and Tree can actually be and contain any indexable type. If this pointer isn't enough to send you in the right direction, I'll try to actually write an example when I have a real keyboard in front of me :) -- Zach (Top-posted in HTML from a phone) On Sun, Apr 22, 2018, 08:54 劉權陞 <01patrick...@gmail.com> wrote: > To deposit a nodes in the tree (adding a new node), for example: put 3: {} > in the Tree branch at branch tuple (2, 4, 1, 5) . > If don't use : > def f(T,k,v): > m=len(T) > if m==0: > Tree[k]=v > elif m==1: > Tree[T[0]][k]=v > elif m==2: > Tree[T[0]][T[1]][k]=v > elif m==3: > Tree[T[0]][T[1]][T[2]][k]=v > elif m==4: > Tree[T[0]][T[1]][T[2]][T[3]][k]=v > elif m==5: > Tree[T[0]][T[1]][T[2]][T[3]][T[4]][k]=v > ... > > f( (2, 4, 1, 5),3,{}) > > Is there a dynamic approach(the node tuple can be any length) > I want to create a function like f(branch_tuple,key,value) > > Tree = {1: {2: {3: {...}, 4: {...}, ...}, 3: {2: {...}, 4: {...}, ...}, 4: > {2: {...}, 3: {...}, ...}, ...}, 2: {1: {...}, 3: {...}, 4: {...}, ...}, 3: > {...}, 4: {...}, ...} > > *(... indicates omission) > * (Node tuple represent one of the branches) > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using the Nimblenet Library in Python 3.6
On Thu, Apr 5, 2018 at 3:39 AM, Alan Gauld via Tutorwrote: > On 05/04/18 04:02, Mark Lawrence wrote: > >> Python 3.6 has more functionality than 2.7 by definition, but your >> comment implies, at least to me, that 2.7 and 3.6 are chalk and cheese. >> Nothing could be further from the truth and has regrettably been one of >> the reasons for the dreadfully slow uptake of Python 3. > > I disagree. Apart from the superficial language compatibility issues, > which 2.7 can partially address by importing from future, the libraries > are dramatically different. Any non trivial program runs into issues the > minute it starts importing modules. module names are different, function > names within those modules are different, return values and parameter > types are different. > > Given Python programming relies hugely on the modules in the standard > library I find it impossible to produce code that works across 2.7 > and 3.x without significant effort to force compatibility. That's why > tools like six etc exist. > > You may have been luckier than me but in my experience the gap > between the two versions is significant and not to be underestimated. I would appreciate keeping the FUD about the differences to a minimum :). The differences are there and they are significant, but far from insurmountable; in my experience, well-written Python 3 code is fairly trivial to port to Python 2/3. Depending on the quality of the initial Python 2 code, it's not quite as easy to port from 2 to 2/3 or directly to 3 due to Unicode/bytes confusion (made worse if the Python 2 code relies on bad Unicode practices), but they're still very much the same language. However, it does take some effort to port an established Python 2 codebase to Python 3, and to bring the thread back to the original topic, it looks like the author of the package in question is not particularly open to doing the work for their package (but may accept a pull request!). Christine (OP), you may have some luck with opening an issue at https://github.com/jorgenkg/python-neural-network and requesting Python 3 support. I don't have enough experience in the field of machine learning to competently suggest an alternative, but I've heard good things about TensorFlow. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about metaclasses
On Wed, Jan 10, 2018 at 10:08 AM, Albert-Jan Roskamwrote: > Hi, > > > In another thread on this list I was reminded of types.SimpleNamespace. This > is nice, but I wanted to create a bag class with constants that are > read-only. My main question is about example #3 below (example #2 just > illustrates my thought process). Is this a use case to a metaclass? Or can I > do it some other way (maybe a class decorator?). I would like to create a > metaclass that converts any non-special attributes (=not starting with '_') > into properties, if needed. That way I can specify my bag class in a very > clean way: I only specify the metaclass, and I list the attributes as normal > attrbutes, because the metaclass will convert them into properties. You appear to be reimplementing Enum. > Why does following the line (in #3) not convert the normal attribute into a > property? > > setattr(cls, attr, property(lambda self: obj)) # incorrect! Because `cls` is `Meta`, not `MyReadOnlyConst`; `__new__` is implicitly a classmethod and `MyReadOnlyConst` doesn't actually exist yet. When `MyReadOnlyConst` is created by `type.__new__` it will be filled with the contents of `attrs`, so instead of `setattr` you want `attrs[attr] = property(...)`. But once you're past the learning exercise that this is, just use enum.Enum or collections.namedtuple :) -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python
On Thu, Nov 30, 2017 at 2:20 AM, Jeroen van de Venwrote: > Hello, > Can you build these 4 programms for me? No, we will not do your homework for you. However, you can show us the code you've written, describe the problem you're having with it (including the full text of all error messages), and we can help you figure out where you've gone wrong. Regards, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Hi Howard, On Wed, Aug 16, 2017 at 5:36 PM, Howard Lawrence <1019sh...@gmail.com> wrote: > class Address: > def _init_(self,Hs,St,Town,Zip): Your issue is in this line, it should be `__init__` rather than `_init_` (that is, two underscores before and after "init"). Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How does len() compute length of a string in UTF-8, 16, and 32?
On Mon, Aug 7, 2017 at 9:44 PM, boB Steppwrote: > py3: s = 'Hello!' > py3: len(s.encode("UTF-8")) > 6 > py3: len(s.encode("UTF-16")) > 14 > py3: len(s.encode("UTF-32")) > 28 > > How is len() getting these values? And I am sure it will turn out not > to be a coincidence that 2 * (6 + 1) = 14 and 4 * (6 + 1) = 28. Hmm First, make sure you know exactly what is having its length checked. In each of those cases, you're not checking the length of the string, `s`, you're checking the length of the string `s` encoded in various encodings (try each of those lines without the 'len' part). Next, take a dive into the wonderful* world of Unicode: https://nedbatchelder.com/text/unipain.html https://www.youtube.com/watch?v=7m5JA3XaZ4k Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?
On Tue, Aug 1, 2017 at 9:54 AM, Thomas Güttlerwrote: > I have a friend who is a talented shell script writer. He is a linux guru > since > several years. > > He asked me if "if __name__=='main':" is state of the art if you want > to translate a shell script to python. > > I started to stutter and did not know how to reply. The ~~correct~~ pedantic answer is "No, it's `if __name__ == '__main__':`" :) > I use Python since several years and I use console_script in entry_points of > setup.py. > > I am very unsure if this is the right way if you want to teach a new comers > the joy of python. > > In the current context we want to translate a bunch of shell scripts to > python scripts. > > What do you think? It depends on whether you're packaging them up as real Python packages (sdist, wheel, etc.) to be installed in site-packages or similar, or if they're just going to be standalone scripts (single file with a shebang, possibly not even a `.py` extension). If the former, go for the entry points. If the latter, go for `if __name__ == '__main__':`. And there's no real reason not to do both in the former case anyway; it's very convenient to not have to install your script somehow to be able to run it. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] centos 7 - new setup.. weird python!
On Wed, Jul 19, 2017 at 3:48 PM, brucewrote: > Hi. Hi Bruce, > > Testing setting up a new Cnntos7 instance. > > I ran python -v from the cmdline... and instantly got a bunch of the > following! Pretty sure this isn't correct. > > Anyone able to give pointers as to what I've missed. > > thanks > > python -v > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py > import site # precompiled from /usr/lib64/python2.7/site.pyc > # /usr/lib64/python2.7/os.pyc matches /usr/lib64/python2.7/os.py > import os # precompiled from /usr/lib64/python2.7/os.pyc This is correct: this is python's "verbose" mode, which prints out some debugging information, like imports and module cleanup. I think you were looking for the `-V` or `--version` flag. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which DB use with standalone desktop app
On Thu, Jul 6, 2017 at 3:57 AM, Freedom Peacemakerwrote: > Hi Tutors, > I am working on standalone desktop app with tkinter GUI (Python3), and i > dont know which database should i use. I've tried to find solution on my > own but google cant help me. There are some with SQL in name (eg. sqlite3, > MySql), but there are some other NoSql like MongoDB or Redis. Please help > me which one i should use for my app not only from ones i've mentioned. My > database will have max 100 records described by 6-8 columns. Most of them > will be 25 characters max but one will have up to 60. That sounds small enough that you probably don't even need a database, but could just store a JSON file with your data, for example. Otherwise, I'd suggest sqlite3; it's very lightweight and intended for single-user applications like this. You definitely don't need anything as large as MySQL or MongoDB :) Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why use main() ?
On Wed, Jul 5, 2017 at 10:37 AM, David Rockwrote: > This is not a question about using if __name__ == '__main__':. I know > what the difference is between running the script or importing it and > using the value of __name__ to determine behavior. > > This is a question about the benefits of using a main() function vs not. > ie, > > if __name__ == '__main__': > #code goes here > > vs > > > def main(): > #code goes here > > if __name__ == '__main__': > main() > > > I personally find using main() cumbersome, but many examples I come > across use main(). Is there some fundamental benefit to using main() > that I'm missing? In no particular order: testing, encapsulation, and reusability. With a "main()" function (which, recall, can be named whatever you like; it doesn't have to be "main") you can directly call the function in your tests to make sure it acts the way you want. The encapsulation of the "main" code in a "main()" function also reduces your global state (and makes global state a bit more difficult to use), which is usually a good thing. And finally, it makes it possible to use the "main()" function in some other piece of code that imports it. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Coming from R, what's a good IDE editor? I've tried PyCharm and Spyder
On Fri, Jun 2, 2017 at 12:46 PM, C Wwrote: > Dear Python list, > > I am an R user learning Python. What is a good editor? > > 1) Pycharm > PyCharm evaluates the entire script, I just want to change a few lines in > the script. > For example, > > import matplotlib.pyplot as plt > import numpy as np > > x = np.arange(0, 1,0.1) > y = np.sin(2 * np.pi * x) > > plt.figure(1) > plt.clf() > plt.plot(x, y) > plt.show() > > Now, I want to do a scatter plot, but don't want to generate the data > again. I just want the "line by line" evaluation like in R and Matlab. > Basically, you can type in console and add to the existing variables. >From the sound of it, you may be more interested in Jupyter Notebook (jupyter.org) than a "proper editor". Otherwise, I've been happy with a combination of PyCharm and vim. Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading files in Python 3
On Mar 30, 2017 15:07, "Rafael Knuth"wrote: I can read files like this (relative path): with open("Testfile_B.txt") as file_object: contents = file_object.read() print(contents) But how do I read files if I want to specify the location (absolute path): file_path = "C:\Users\Rafael\Testfile.txt" with open(file_path) as file_object: contents = file_object.read() print(contents) The above does not work ... "The above does not work" is not descriptive. How does it not work? Is there a traceback? Does the program stop responding? Does the computer catch fire? In this case, the problem is the bogus Unicode escape that you inadvertently included in your path: `\Us...`. To fix it, either use a 'raw' string (`r"C:\Users\..."`) or use forward slashes rather than backslashes, which Windows is happy to accept. Regards, -- Zach (On a phone) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to access an instance variable of a superclass from an instance of the subclass?
On Wed, Feb 22, 2017 at 10:25 PM, boB Steppwrote: > I am trying to wrap my head around the mechanics of inheritance in > Python 3. I thought that all attributes of a superclass were > accessible to an instance of a subclass. > > Obviously I am horribly misunderstanding something, and being > currently sleepy is not helping my cause. I'll give you a couple of hints. First, try this: print('defining A') class A: print('Setting a on class A') a = 'a on class A' def __init__(self): print('Setting aa on instance of', self.__class__.__name__) self.aa = 'aa in A.__init__' print('defining B') class B(A): print('Setting b on class B') b = 'b on class B' def __init__(self): print('Setting bb on instance of', self.__class__.__name__) self.bb = 'bb in B.__init__' print('Instantiating a') a = A() print('Instantiating b') b = B() Next, have a look at https://docs.python.org/3/library/functions.html#super and in particular the link at the end to Raymond Hettinger's "super considered super" essay. And finally, there's one line you can add to B.__init__ that will get what you're after. I hope this is helpful, I'm sure others will be along with in-depth explanations before long anyway :) Regards, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Test for type(object) == ???
On Fri, Feb 10, 2017 at 7:34 PM, boB Steppwrote: > So my question is why does "type(5)" result in "", but > the correct Boolean test is "type(5) == int"? I suspect it has > something to do with the built-in attributes of Python objects that I > currently know so very little about. Try `help(repr)` and `int` on its own at the interactive prompt, and see if that clarifies anything. I hope that might be enough to nudge you in the right direction, but if not, come back and ask :) -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple tabs using tkinter
On Tue, Feb 7, 2017 at 12:59 PM, Alan Gauld via Tutor <tutor@python.org> wrote: > On 07/02/17 16:41, Zachary Ware wrote: > >> Full disclosure, I've never actually used Tix beyond making it build >> with the rest of CPython on Windows and making sure it actually worked >> on one of my Linux buildbot workers. I have only ever seen it as a >> maintenance headache :) > > The beauty of Tix is that it is a full superset of Tkinter > so you can just put this at the top and it converts your > code to use Tix: > > replace > > import Tkinter > > with > > import Tix as Tkinter That's just because tix.py does "from tkinter import *". You can achieve the same by doing 'from tkinter import *;from tkinter.ttk import *' (in a separate 'tk.py' if you want everything namespaced in your code). > But Tix has over 40 extra widgets including a tabbed notepad, > balloon, meter, shell and and a very powerful (but undocumented!) > grid control. Very little of tkinter is actually documented outside of the official Tcl/Tk docs, unfortunately. How does tix.Grid differ from the standard grid geometry manager (.grid() method on widgets)? > The most important and commonly used seem to have been > incorporated into the latest ttk, but not all of them. Which ones are missing? I'd recommend raising issues against Tk for having them added. >> "Less available" rather than "unavailable" :). Tix ships with Tcl/Tk >> with CPython on Windows; on Linux, you'd need to install it separately >> from Tcl/Tk and python/tkinter. I honestly don't have a clue how >> you'd get it on macOS or any other platform that doesn't provide it in >> a system repository. > > It should be easy since its just native Tcl code, there's no C > involved so far as I know (I haven't checked!). So anywhere Tcl > runs Tix should work. There's some Tcl, but mostly C; see http://svn.python.org/view/external/tix-8.4.3.x/ (particularly the 'generic', 'unix', and 'win' directories). -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple tabs using tkinter
On Mon, Feb 6, 2017 at 7:31 PM, Alan Gauld via Tutorwrote: > On 06/02/17 16:40, Pooja Bhalode wrote: > >> I was wondering if someone could help me regarding multiple tabs in >> tkinter. > > Look at the tabbed notebook in the Tix module. > It should do what you want. ttk rather than Tix; Tix is unmaintained and soft-deprecated in 3.6+. ttk provides most of the useful parts of Tix, is maintained as part of Tk, and also looks significantly more native than classic Tk or Tix. Tix is also less available on platforms other than Windows, whereas ttk is present in any Tk 8.5 or greater. > I give a tutorial on its use in my recent book but you can > also find online tutorials, especially in Tcl (Python ones > are much harder to find) > >> Also, I was wondering if there is a way in tkinter to create an explorer >> bar that we see in finder in OS Mac or windows. I found a way to do that >> using wxpython, but was wondering if there is a way using tkinter. > > Tkinter is a relatively low level GUI toolkit. You can > build most things but you have to start with the basic > widgets. So an explorer bar is just an Entry widget to > which you can attach any functionality you care to create. Also have a look at ttk.Combobox, which combines an Entry and Listbox (and, I think, if the list is long enough, a Scrollbar) into a drop-down menu widget. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] overriding brackets in lvalue assignment possible?
On Tue, Dec 27, 2016 at 10:48 AM, James Hartleywrote: > I can successfully override __getitem__() for rvalues, but the following > example shows that more is required when used as an lvalue: > > ===8<- > #!/usr/bin/env python > > class Foo(): > def __init__(self, n): > self.d = dict.fromkeys([i for i in range(0, n)]) > > def __getitem__(self, i): > return self.d[i] > > def main(): > foo = Foo(4) > print(foo[0]) > foo[0] = 2 # not as an lvalue? > print(foo[0]) > > if __name__ == '__main__': > main() > ===8<- > > Python 3.4 generates the following output when this example is executed: > > None > Traceback (most recent call last): > File "./test.py", line 17, in > main() > File "./test.py", line 13, in main > foo[0] = 2 > TypeError: 'Foo' object does not support item assignment > > I am surprised that the error states that the object itself cannot accept > assignment. From the C++ perspective, the underlying dictionary should be > exposed. Does Python overloading allow use of bracket overriding in > lvalues? Hi James, You're looking for __setitem__(), see https://docs.python.org/3/reference/datamodel.html#object.__setitem__ Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.x and Sqlite3
Hi Greg, On Tue, Oct 11, 2016 at 3:54 PM, Greg Schmitwrote: > On FreeBSD I built lang/python34 from source and when I run python 3.4 I > cannot import sqlite3. I thought it was being packaged with python 3.4. Am I > incorrect in this assumption? This is more the kind of fare that python-list is good for; this list is more for learning how to use Python. In any case, you'll need to make sure you have sqlite3 and its headers installed before building Python. At the end of the 'make' step, you probably got a message saying "The necessary bits to build these optional modules were not found:" with _sqlite3 listed underneath it. There may also be other useful modules listed there that you may want to install the dependencies for, such as readline or _ssl. Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pytsk
Hi Peter, On Fri, Apr 29, 2016 at 8:15 AM, Tees, Peter (EthosEnergy)wrote: > Hi folks > > I'm pretty new to Python and programming, I've done the first four modules of > the Python course at Coursera.org to get started > > Now I want to put what I've learned to good use, based on the articles by > David Cowen at the Hacking Exposed blog and in particular his series > "Automating DFIR - How to series on programming libtsk with Python" (which is > Python 2.7, same as Coursera.org) > > The very first thing to be done, after installing Python, is to grab a > Windows installer for the pytsk library from here > https://github.com/log2timeline/l2tbinaries/blob/master/win32/pytsk3-4.1.3-20140506.win32-py2.7.msi > > But that link doesn't work (Page 404), and any other downloads I've seen so > far refer either to binding to The Sleuthkit or refer to pytsk3 which I don't > think is what I need > > Can anyone point me to a Windows 32-bit installer for a pytsk library that > will work with Python 2.7? I can't find one easily, but it does look like pytsk3 is what you want -- looking at the link you provided, the name is 'pytsk3-...'. So what should be sufficient is to install the Microsoft Visual C++ Compiler for Python 2.7 [1], then run 'python -m pip install pytsk3'. That should be enough to get you going. [1] https://aka.ms/vcpython27 Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] asyncio or threading
My apologies for taking so long to reply here again, it's been a busy couple of weeks. On Mon, Feb 15, 2016 at 7:18 PM, Alan Gauld <alan.ga...@btinternet.com> wrote: > On 15/02/16 21:08, Zachary Ware wrote: >> This is not all asyncio can do. Callbacks are only one way of using it, the >> other, more common method is to use coroutines such that most of your code >> reads almost like regular, synchronous code. > > I'm not sure about "most common" since every single example of > asyncio I've seen so far has used callbacks not coroutines. > (Not that I've seen too many examples, but the ones I have seen > all used callbacks.) Could you point me towards some of those examples? >> I don't think this is quite true either; I've heard the JavaScript >> equivalent referred to frequently as "callback hell", > > A slanderous comment that's not really deserved :-) Sorry; my information on this point is all secondhand (or worse) as I've not used NodeJS and have somehow even avoided JavaScript as a whole. Take anything I say about JavaScript/NodeJS with a healthy measure of salt :). My impression was that the callback style naturally leads to doing things where callbacks are chained several layers deep, which makes things hard to read and takes concentrated effort (slight though it may be) to avoid. > As a matter of interest which tutorials on asyncio cover this best? > I've only read one closely and it was all about callbacks but > it impressed me enough to become an asyncio fan. However I'm > certainly interested in finding out more on the coroutine front. Frankly, I have yet to see a *good* asyncio tutorial, but haven't looked very hard either. I learned how to use it from the reference docs (which are also somewhat lacking still, I had to fix some issues in the docs as I was learning it) and trial-and-error, which actually worked surprisingly well. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] asyncio or threading
On Feb 15, 2016 1:25 PM, "Alan Gauld"wrote: > > On 15/02/16 13:09, CMG Thrissur wrote: > > > I just wanted an opinion on the subject, asyncio and threading both seam > > to do the same job, but i feel threading is better because of the > > multiple ways i can control it. > > They do similar jobs but asyncio uses threading in the background > and I believe it's at OS level not Python native threading (which > has some significant issues). This isn't quite accurate. asyncio only uses threading if you explicitly tell it to use a thread for something, otherwise everything is run in coroutines in the main thread, which are based on generators. Also, Python threads are native OS threads, but the threading module does a bit of management to allow you to keep track of them. > However, the biggest differences are in the conceptual usage. asyncio is > intended primarily for event driven scenarios where something happens > that triggers a long running (eg. a hundred milliseconds or longer, > say). You add the task to the event loop and it gets processes as and > when it gets scheduled. You don't care and just wait for it to complete > after which it will call your callback function. So if you have a > scenario where tasks can be scheduled and forgotten about then asyncio > is ideal. The obvious use case is a server receiving > messages over a network and returning results when done. This is not all asyncio can do. Callbacks are only one way of using it, the other, more common method is to use coroutines such that most of your code reads almost like regular, synchronous code. > If you want to do something in near real-time with a separate > thread where you comunicate between two (or more) threads then > asyncio is not such a good fit and conventional threading will > likely be better. But it's a lot harder to get right. With asyncio > all the hard threading bits are done for you. This doesn't quite apply, since asyncio doesn't use threads :). > Finally, if you have done any work with NodeJS using Javascript > you are likely to find asyncio a natural fit to your style. I don't think this is quite true either; I've heard the JavaScript equivalent referred to frequently as "callback hell", which is not the idiomatic usage of asyncio. Callbacks are supported, because they are useful in several instances, but they should not be the only (or even main, usually) way asyncio is used. -- Zach (On a phone, apologies for brevity) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] asyncio or threading
On Feb 15, 2016 1:12 PM, "CMG Thrissur"wrote: > > Hello, > > I just wanted an opinion on the subject, asyncio and threading both seam to do the same job, but i feel threading is better because of the multiple ways i can control it. > > Just want get the groups opinion based on there experience in using asyncio or threading in real life problems. This is more of a python-list subject, I think you would receive more and better answers there (at the cost of a lot more posts to the thread that are only tangentially related to your query). To answer with my own vague impressions (based on experience, but not analyzed in depth): asyncio is substantially easier to work with, while threads take a lot more thought to make sure you aren't trampling on what another thread is doing. It's also quite easy to use threading for just some parts that need it, like a blocking function that may take a long time to complete, while using asyncio for everything else (see BaseEventLoop.run_in_executor()). -- Zach (On a phone) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Missing Standard Libraries on Python 3.5 for Mac
Hi Andrew, On Tue, Nov 3, 2015 at 11:20 AM, Andrew Machenwrote: > Hi, > > I am new to Python, and I am trying to use a Python Standard Library, namely > ‘unicodedata’, however it appears to be missing (others are also missing) > from the built-in libraries that come with Python 3.5 for Mac. > > I have searched the following directory, but have not found the library: > > /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5 Have you tried importing it? If importing it works, you can then find where it lives by checking the __file__ attribute: import unicodedata print(unicodedata.__file__) > I have tried reinstalling Python 3.5 and also tried Python 3.4.3, and neither > install the ‘unicodedata’ library. Is there anyway to install it manually? It should be included with your installation, assuming you're using the package from python.org. If you are unable to import it, please raise an issue on the bug tracker at bugs.python.org. For the record, here's where unicodedata lives on my Mac: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload/unicodedata.cpython-35m-darwin.so Note that unicodedata is implemented in C, so it does not have a .py extension. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Messy - Very Messy string manipulation.
On Wed, Oct 28, 2015 at 10:09 AM, Vusa Moyowrote: > Hi Guys, > > I've written a script to remove vowels from a string/sentence. > > the while loop I'm using below is to take care of duplicate vowels found in > a sentence, ie > > anti_vowel('The cow moos louder than the frog') > > It works, but obviously its messy and n00by. Any suggestions on how I can > write this code better? First off, the code that works (by "works" I mean "passes its tests") is far better than the code that doesn't, no matter what form that code takes. That said, there are several tricks you can use to significantly shorten your function here. > def anti_vowel(text): I'd rather name this "remove_vowels", since that's what it *does* rather than what it *is* is an English sense. > vowel = ['a', 'e', 'i', 'o', 'u'] > VOWEL = ['A', 'E', 'I', 'O', 'U'] Strings can be thought of as tuples optimized for characters, with some special methods. Tuples, in turn, can be thought of as immutable lists. So the above can be shortened to: vowel = 'aeiou' VOWEL = 'AEIOU' Using one of those special methods I mentioned: vowel = 'aeiou' VOWEL = vowel.upper() But do we really need two separate vowel containers? vowels = 'aeiou' all_vowels = vowels + vowels.upper() Or to save a name, and some typing: vowels = 'aeiou' vowels += vowels.upper() > manip = [] > > for i in text: > manip.append(i) Any time you have the pattern "create an empty list, then append to it in a for loop", think "comprehension". The above could be shortened to: manip = [i for i in text] Or, since the list constructor takes an iterable argument and strings give characters upon iteration: manip = list(text) But we don't really need manip at all, as I'll show further down. > fufu = 0 > # > while fufu < 16: This is a fairly weird way to spell "loop 8 times", if I'm honest :). A more idiomatic approach would be to get rid of 'fufu' and do this instead: for each in range(8): Which loops 8 times and assigns the number of the loop (0-7) to the name 'each' each time around. 'each' could be any valid identifier ('_' is commonly used for this), 'each' just makes sense reading the line as English. > for x in vowel: > if x in manip: > manip.remove(x) > > for y in VOWEL: > if y in manip: > manip.remove(y) Above, we combined 'vowel' and 'VOWEL' into 'vowels', so these can be shortened into a single loop by removing the second loop and changing the first to iterate over 'vowels' instead of 'vowel'. But instead of removing values from a list we just built, it's easier to build the list without those values in the first place, see below. > fufu = fufu + 2 This line goes away with the change from 'while' to 'for each in range'. > strong = ''.join(manip) > return strong I suspect this was meant to be 'string' :). Anyway, 'return' can return any expression not just a name, so this could be just: return ''.join(manip) So, what was I talking about with not needing 'manip' and building the list without the values in the first place? Combining some other stuff mentioned above, we can build a list of the characters of the given text, minus vowels, using a comprehension: list_of_chars_without_vowels = [c for c in text if c not in vowels] To better understand what's going on here, you can "unroll" the comprehension by initializing the name to an empty list, then moving the initial expression (the "c" in "c for ...") to an append call all the way inside: list_of_chars_without_vowels = [] for c in text: if c not in vowels: list_of_chars_without_vowels.append(c) 'list_of_chars_without_vowels' is then in the same state your 'manip' was in after the loops, so the loops go away entirely. 'list_of_chars_without_vowels' is an unwieldy name, but we don't actually need to name it: return ''.join([c for c in text if c not in vowels]) And one final optimization (which in this case is more of a finger optimization than a performance optimization), we can drop the square brackets to turn the list comprehension into a generator expression: return ''.join(c for c in text if c not in vowels) The difference between the two above statements is that the first calculates the entire list of characters, then passes it to ''.join(), which iterates through the list to create the final string, while the second creates a generator and passes it to ''.join(), and the generator calculates and yields the next character each time ''.join() calls next() on it. To put everything together, here's my final version, with a docstring, a punny Easter egg, and a very simplistic test that is not adequate testing: import random def remove_vowels(text): """Remove all vowels from 'text' and return the result.""" vowels = 'aeiou' + random.choice(['y', '']) # "and sometimes y"
Re: [Tutor] Messy - Very Messy string manipulation.
On Wed, Oct 28, 2015 at 11:09 AM, Zachary Ware <zachary.ware+py...@gmail.com> wrote: >assert remove_vowels('Did It work? Looks like.') == 'Dd t wrk? Lks Lke.' Of course I typo'd here (that's what you get for not testing!): there should be no final 'e' and the last 'L' should be lower-case. assert remove_vowels('Did It work? Looks like.') == 'Dd t wrk? Lks lk.' -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Messy - Very Messy string manipulation.
On Wed, Oct 28, 2015 at 11:09 AM, Zachary Ware <zachary.ware+py...@gmail.com> wrote: >return ''.join(c for c in text if c not in vowels Looking again, I see I typo'd here too. There should of course be a ')' at the end. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working collaboratively (was: accessing modules found throughout a package?)
On Mon, Oct 19, 2015 at 2:53 PM, Alex Kleiderwrote: > On 2015-10-19 12:37, Ben Finney wrote: >> Work >> with other Python programmers on a common code base, and watch your >> skills broaden and improve! > > > How I wish I could find such collaborator! > Are there any "starter level" PyPi projects the maintainer of which > might consider a novice collaborator? I would have assumed that > such an animal doesn't exist. Most maintainers of open source software will gratefully accept patches from anybody of any skill level (after proper review), though there's always the possibility that a patch will be politely rejected (if it's rejected impolitely, that's their problem, not yours). The choice of project to contribute to is really up to you. Pick one that you like and know fairly well, and preferably make a contribution that will make some difference to you and your use of the project. And if you can't find a PyPI project you'd like to contribute to, you could always give a shot to working on CPython itself -- see https://docs.python.org/devguide/ for a guide to getting started with that. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Type Error
On Mon, Sep 14, 2015 at 9:29 AM, richard kapplerwrote: > everything works except the os.remove(file) which gives the following error: > > Traceback (most recent call last): > File "DataFeedBatch.py", line 104, in > os.remove(file) > TypeError: coercing to Unicode: need string or buffer, file found > > I don't understand the error os.remove() expects a filename, and you're passing it a 'file' object. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How should my code handle db connections? Should my db manager module use OOP?
On Aug 26, 2015 9:03 PM, Steven D'Aprano st...@pearwood.info wrote: - If your database lives on a NTFS partition, which is very common for Linux/Unix users snip these issues, especially on Linux when using NTFS. Surely you mean NFS, as in Network FileSystem, rather than NTFS as in New Technology FileSystem? :) -- Zach (On a phone) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is it possible to archive subsets of data from an SQLite db and restore it later?
On Mon, Aug 17, 2015 at 10:44 PM, boB Stepp robertvst...@gmail.com wrote: My wife had an interesting request tonight: Would it be possible to have two dbs, one that is the current working db, and the other an archival db for students who have left the school? If yes, then the archival db would need to be able to serve two functions: 1) If the teacher gets a request for certain types of reports, then she should be able to generate them from the archival db just as she would be able to from her working db. She would want the archival db to retain the same structure and functionality as the current working db. 2) If a student returns to the school as a student, it should be possible to reintegrate all of that student's data from the archival db back into the current working db. I see this more as an interesting problem right now as I think it would take a long time to fill up SQLite's 2 TB max size. It seems to me like it should be doable, but might be quite complicated. OTH, I don't know much about SQL yet, and it might actually be more trivial than I can currently imagine. So I thought I would ask the group to see which category of problem this truly is. i think rather than try to move data between two DBs, I'd just add a Boolean 'currently_enrolled' column to the Students table. When you care about whether the student is currently enrolled or not, add 'WHERE currently_enrolled = true' (or however that needs to be spelled) to your query. When the student graduates/moves/re-enrolls, just update that value. I'm not hugely experienced with databases/SQL myself either, though. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Does composition only work with particular instances of objects?
On Thu, Aug 13, 2015 at 11:31 PM, boB Stepp robertvst...@gmail.com wrote: I was looking at an example illustrating composition from the book, Introducing Python by Bill Lubanovic on p. 140: class Bill: def __init__(self, description): self.description = description class Tail: def __init__(self, length): self.length = length class Duck: def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print('This duck has a', bill.description, 'bill and a', tail.length, 'tail.') Here I was mildly surprised that bill and tail were not Bill and Tail, and in the about method that self.bill was not used in place of bill.description, etc. Something went wrong here, either with the example itself or your copying of it. Your instinct is correct, it should be 'self.bill.description' rather than 'bill.description': the Duck.about method as written above will only work in situations where 'bill' and 'tail' happen to be defined in the calling scope. The about method should be: def about(self): print('This duck has a', self.bill.description, 'bill and a', self.tail.length, 'tail.') Continuing: tail = Tail('long') bill = Bill('wide orange') duck = Duck(bill, tail) duck.about() This duck has a wide orange bill and a long tail. Before you fix the about method as I suggested above, try this again but do `del bill, tail` before you call `duck.about()`; the failure may be somewhat enlightening. So I naively thought I could do the following: bill0 = Bill('narrow rainbow') tail0 = Tail('ginormous') And was surprised by: duck.about() This duck has a wide orange bill and a long tail. duck0 = Duck(bill0, tail0) duck0.about() This duck has a wide orange bill and a long tail. From this I am forced to conclude that composition will only work with particular instances of objects and not with any old objects created from their respective classes. Is this understanding correct? Very much not :). You were correct to think this was meant to give you 'This duck has a narrow rainbow bill and a ginormous tail.', but the about method had a serious bug. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] _ vs. _name vs. __name vs. name_ vs. __name__ usages
On Saturday, July 25, 2015, boB Stepp robertvst...@gmail.com javascript:_e(%7B%7D,'cvml','robertvst...@gmail.com'); wrote: 5) __name__ is meant to be used only by the creators of Python for their special built-in methods, such as __init__, __new__, etc. Everything up to this point was pretty accurate. You're only half right with this one, though; __dunder__ names are ones that you should only use when hooking into the magic of the interpreter. That is, you should not define your own __dunder__ names, but feel free to use ones that have been defined by the implementation and documented as the way to do something. For example: class Spam: def __init__(self, value): self.value = value def __getitem__(self, key): return self.value assert Spam(42)['eggs'] == 42 __getitem__ is the documented method to implement to allow instances of your class to be indexed like a list or dict. Are my understandings above correct or flawed? For (3), it seems to me that one would normally be able to use the simpler _name construction from (2). What would be a best-practice example of when name mangling *should* be used? I have yet to ever see a place where name mangling was warranted. I have been severely annoyed by it before, though. To make a particular class work the way I wanted it to, I had to subclass it and explicitly override a couple of mangled names. In my opinion, name mangling should never be used unless overriding the value will set your CPU aflame. Likewise, it seems that normally (4) should never be needed, though I have a feeling that I have seen something in tkinter recently that suggests some exceptions, but I cannot (yet) bring it to mind. There are a couple of methods in tkinter that accept an 'in_' keyword argument, where in Tcl it is documented as 'in', which is a Python keyword. In code that's not interfacing with something else that uses a Python keyword, it's usually best to just find a different name. And for (5), surely I should never violate this one? It seems that in some future edition of Python they might add any particular __name__ that I might try to use presently in their future version of Python (however miniscule that possibility might actually be). Right, don't make up your own __dunder__ names. Hope this helps, -- Zach (On an iPad) -- Sent from Gmail Mobile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get a Tkinter window to print a color copy of itself as a .pdf file?
On Apr 15, 2015 9:38 AM, boB Stepp robertvst...@gmail.com wrote: Perhaps I am being foolish! But I do have my reasons, which, in this case, is I wanted to take advantage of the pack and grid geometry managers. These two tools seem to make the positioning of the widgets much easier. Unless I am missing something, in a Canvas container I will have to assign pixel coordinates for everything, which sounds like a lot more work! Couldn't you just map a single Frame widget on the canvas, and use the Frame as your outer container? -- Zach On a phone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get a Tkinter window to print a color copy of itself as a .pdf file?
On Apr 15, 2015 9:59 AM, boB Stepp robertvst...@gmail.com wrote: On Wed, Apr 15, 2015 at 8:50 AM, Zachary Ware zachary.ware+py...@gmail.com wrote: On Apr 15, 2015 9:38 AM, boB Stepp robertvst...@gmail.com wrote: Perhaps I am being foolish! But I do have my reasons, which, in this case, is I wanted to take advantage of the pack and grid geometry managers. These two tools seem to make the positioning of the widgets much easier. Unless I am missing something, in a Canvas container I will have to assign pixel coordinates for everything, which sounds like a lot more work! Couldn't you just map a single Frame widget on the canvas, and use the Frame as your outer container? You are SMART, I am NOT! That sounds like a great idea!! To almost quote Jacob Kaplan-Moss from his keynote talk at PyCon this year, Hi, I'm [Zach], and I'm a mediocre programmer :) Is this the intent of the Tkinter design to provide print functionality? To always start with a Canvas container? I honestly have no idea. -- Zach On a phone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] annoying directory structure
On Thu, Apr 9, 2015 at 10:07 PM, Jim Mooney cybervigila...@gmail.com wrote: [Previously, I wrote:] I'll need to see some actual code (namely, where and how you used os.walk) to have any real idea of what's going on. The online docs for os.walk have a pretty good explanation and example. This worked. I didn't know why I got doubled strings, but print concatenated them so I printed to a file, and the text lines all open an mp4 in windows explorer, as expected. Unfortunately they aren't in order, so I guess I'll have to actually read up on walk. I just wanted to knock it out quickly by figuring out the walk output format, and get on with the course ;') tutfiles = open('tutfiles.txt', 'w') p = os.walk('I:\\VIDS\\Learn Python Track\\') for triplet in p: if triplet[2] == []: continue else: if 'mp4' in triplet[2][0]: print(triplet[0] + '\\' + triplet[2][0], file=tutfiles) tutfiles.close() Frankly, that's a bit horrifying :). I'm glad you came up with a solution that works for you using the tools available to you, but it's far from idiomatic Python code. Here's how I would write it (please excuse any syntax errors; I'm not testing it. Logic errors, I'll take the blame :) ). import os def get_filenames(top_level_dir): all_video_files = [] for dir, dirs, files in os.walk(os.path.abspath(top_level_dir)): for filename in files: if filename.endswith('.mp4'): all_files.append(os.path.join(dir, filename)) return all_video_files print(*get_filenames(your root directory), sep='\n') If you need them sorted in some particular way, you can sort the list before printing it, using the sort() method of the list (and probably the 'key' keyword argument). Please take a look at this and try to understand what it's doing, and ask about anything that doesn't make sense (that's the most important part!). Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] annoying directory structure
On Thu, Apr 9, 2015 at 2:02 PM, Jim Mooney cybervigila...@gmail.com wrote: The safest method would probably be to do `pip freeze requirements.txt`, copy the requirements.txt file to the new machine, and run `pip install -r requirements.txt --Zach I looked at pip3 help (windows) and don't see a -r command. However, it does work. How do I get the invisible commands ;') Try `pip3 help install` :) Another question. I have a set of training vids. Unfortunately, each vid is in a subdir inside a subdir inside a subdir inside a subdir inside the directory. Going down, down, down, up, up, up to nab them (they're short) and remember where I am, is annoying. How do I use python to get a simple straight list of the vids in directory order - full windows path - so I can just copy and plug the paths into windows explorer, one at a time? Have a look at os.walk(), it will enable you to walk (hence the name) through all directories in a tree. Take a crack at it, and if you have trouble come back with some code for us to look at. You may also need os.path.abspath to get the full path. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] migrating python to a new machine
On Apr 8, 2015 3:39 AM, Jim Mooney cybervigila...@gmail.com wrote: General question. I'm thinking of moving to a new machine although I hate to abandon trusty XP. Will I have to reinstall all my pip installed modules or can I just copy the site-packages directory? And if so, is anything else needed, such as where pip keeps its uninstall info? The safest method would probably be to do `pip freeze requirements.txt`, copy the requirements.txt file to the new machine, and run `pip install -r requirements.txt` there. That way you definitely get everything (and you can save the requirements file for backup purposes). Finally, is there such a thing as a standalone Python? I use a number of standalone programs so it seems to me it should be possible. Do you mean like a portable app, that doesn't write to the registry and keeps everything in one folder? You can try PortablePython; I used it some several years ago and it seemed to work fine (but that was when I was just starting with Python). Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unexpected results using enumerate() and .split()
On Tue, Mar 31, 2015 at 3:23 PM, boB Stepp robertvst...@gmail.com wrote: The following behavior has me stumped: Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. L = ['#ROI:roi_0', '#TXT:text_0', '#1:one^two^three'] for i, item in enumerate(L): subitems = item.split(':') if subitems[0] == '#ROI': print subitems[1] if subitems[0] == '#TXT': print subitems[1] if subitems[0] == '#1' or '#2': Here's your problem: #2 is always true. Try if subitems[0] in ['#1', '#2']: -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unexpected results using enumerate() and .split()
On Tue, Mar 31, 2015 at 3:37 PM, boB Stepp robertvst...@gmail.com wrote: On Tue, Mar 31, 2015 at 3:28 PM, Zachary Ware zachary.ware+py...@gmail.com wrote: On Tue, Mar 31, 2015 at 3:23 PM, boB Stepp robertvst...@gmail.com wrote: The following behavior has me stumped: Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. L = ['#ROI:roi_0', '#TXT:text_0', '#1:one^two^three'] for i, item in enumerate(L): subitems = item.split(':') if subitems[0] == '#ROI': print subitems[1] if subitems[0] == '#TXT': print subitems[1] if subitems[0] == '#1' or '#2': Here's your problem: #2 is always true. Try if subitems[0] in ['#1', '#2']: Thanks, Zach! About the time your reply arrived I was starting to realize that my '#1' or '#2' might not be doing what I thought. In the Python Pocket Reference I was just looking at: X or Y If X is false then Y; else X. I forgot that different languages have different interpretations of or. In this case, the differing languages being Python and English :). Also, not that since you aren't using the index for anything, you don't need to use enumerate() to iterate over the list. Just do for item in L:. Of course, if you actually use the index in the real code that I assume this was cut out of, keep enumerate; it's the right tool for the job. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file exists question
On Mar 9, 2015 7:25 PM, Steven D'Aprano st...@pearwood.info wrote: What I really want is an option to open() that only opens a new file, and fails if the file already exists. If I'm not mistaken, this is the 'x' open mode, added in Python 3.4 (or maybe 3.3, I forget). -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3 simple socket issue
On Wed, Feb 18, 2015 at 9:48 AM, Juan C. juan0christ...@gmail.com wrote: h1We\'re sorry.../h1p... but your computer or network may be sending automated queries. To protect our users, we can\'t process your request right now./p/divdiv style=margin-left: 4em;See a href= https://support.google.com/websearch/answer/86640;Google Help/a for more information.br/br//divdiv style=text-align: center; border-top: 1px solid #dfdfdf;a href=https://www.google.com;Google Home/a/div/body/html' Process finished with exit code 0 Why a I getting 403? The code seems fine. Read the response you got back, particularly the link they sent you: https://support.google.com/websearch/answer/86640 The code is fine, the action is not in line with what Google will allow you to do. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to easily recover the current index when using Python-style for loops?
On Thu, Feb 5, 2015 at 11:30 AM, boB Stepp robertvst...@gmail.com wrote: Python 2.4.4, Solaris 10. a_list = [item1, item2, item3] for item in a_list: print 'Item number', ???, 'is:', item Is there an easy, clever, Pythonic way (other than setting up a counter) to replace ??? with the current index of item in a_list? Added in Python 2.3: https://docs.python.org/2/library/functions.html#enumerate a_list = [item1, item2, item3] for i, item in enumerate(a_list): print 'Item number', i, 'is:', item -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why is an instance smaller than the sum of its components?
On Tue, Feb 3, 2015 at 3:59 PM, Emile van Sebille em...@fenx.com wrote: On 2/3/2015 1:12 PM, Jugurtha Hadjar wrote: 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? neither foo() nor bar() return anything explicitly, so both return the default none This is not correct, foo() and bar() return a foo instance and a bar instance, respectively; not None. For the OP: while this will probably be a nice exercise for learning more about Python's internals, please keep in mind that 9 times out of 10 you won't need to worry about memory usage in Python, especially not before you've proven to yourself that your program is using more memory than is acceptable. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to change default path output of 'logging'?
On Monday, December 22, 2014, Juan Christian juan0christ...@gmail.com javascript:_e(%7B%7D,'cvml','juan0christ...@gmail.com'); wrote: I have a 'logging' on my code using: import logging ... logging.basicConfig(filename=bumpr.log, level=logging.INFO) ... The thing is that the default location of this output when running via Windows Task Scheduler is 'C:/Windows/System32'. Is there a way to change the location of the output of this module? I want it to output where my 'main.py' is. That location is not a function of logging, it's a function of running via Windows Task Scheduler, which apparently starts the program with a current directory of C:\Windows\System32. The solution is to give logging an absolute path for the output file (which you can base of off __file__, something like os.path.join(os.path.dirname(__file__), bumpr.log)) . Hope this helps, -- Zach -- Sent from Gmail Mobile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Philosophical question about string slicing from end of a string
On Mon, Nov 24, 2014 at 12:32 PM, boB Stepp robertvst...@gmail.com wrote: Python 2.7.8 Win7Pro str = 0123456789 str[-1] '9' str[-3:-1] '78' str[-3:] '789' I understand that the above is the way it is in Python, but I am puzzled why the designers did not choose that str[-3:-1] returns '789', especially since str[-1] returns '9'. What is the reason for choosing Python's actual behavior? For the same reason as this behavior with positive indices: s = '0123456789' s[1] '1' s[3] '3' s[1:3] '12' Here's what you can do with it: s[-5:-3] + s[-3:-1] == s[-5:-1] True len(s[-5:-3]) == -3 - -5 True Think of slicing as everything from this index (-3) up to but not including (:) this index (-1). Have I clarified or muddied it for you? :) Regards, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Philosophical question about string slicing from end of a string
On Mon, Nov 24, 2014 at 1:06 PM, boB Stepp robertvst...@gmail.com wrote: On Mon, Nov 24, 2014 at 12:57 PM, Zachary Ware zachary.ware+py...@gmail.com wrote: [...] Have I clarified or muddied it for you? :) Clarified, I believe, if my following statements are correct: I did not consider that the behavior was symmetric with positive indices. So, index 0 is the center relative to which positive and negative indices create identical behaviors. Hmm, either I'm not quite following you, or that's not quite right. For the purposes of slicing, 0 is positive and slices that have either all positive or all negative indices behave the same way. Mixing positive and negative indices is of course possible, but takes a little bit more thought since you're counting from opposite ends. Also note that there's no way to get the last member with a negative second index. [Received while writing the above] On Mon, Nov 24, 2014 at 1:16 PM, boB Stepp robertvst...@gmail.com wrote: Hmm. There is a flaw in my observed symmetry in that str[0:3] and str[-3:0] do not behave the same as the latter returns an empty string. Correct. Here's another way to think about negative indices, particularly for converting between positive and negative indices: s[-5:-3] '56' len(s)-5 5 len(s)-3 7 s[len(s)-5:len(s)-3] '56' s[5:7] '56' So, when you try to do s[-3:0], you're doing s[len(s)-3:0], which equates to s[7:0]. Building from my example with the length of the slice in my previous message, the length of that slice would be 0 - 7, or -7, which obviously won't work very well! Instead of bailing out with an error there, Python just gives you the shortest substring it can, ''. [*] Btw, I've been using 's' instead of 'str' just because it's good practice not to shadow builtin names like 'str'. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ran into a problem with pip install
On Mon, Nov 24, 2014 at 10:28 PM, Clayton Kirkwood c...@godblessthe.us wrote: I was trying to pip install beautifulsoup and ran into the following error. It appears to be 2.x because of the print. Your diagnosis is correct, beautifulsoup 3.2.1 is written for Python 2. I am installing to a python 3.4.2. What do I need to do? Install beautifulsoup4. Just to note, I know nothing about beautifulsoup, having never used it. I determined the proper solution by doing a Google search for beautifulsoup, which turned up two different PyPI links as the 4th and 5th results. Opening both of them, the one for 'BeautifulSoup 3.2.1' says This package is OBSOLETE. It has been replaced by the beautifulsoup4 package. You should use Beautiful Soup 4 for all new projects. I tried to log a bug report to PyPI Bug Reports but that apparently isn’t the cool thing to do. What do you mean by that? However, note that this was not a PyPI bug; if anything, it's a bug in beautifulsoup's setup.py not specifying that it is a Python2-only package, which is not likely to change since the package is marked as obsolete. By the way, it is good to confirm that there is actually a reproducible bug before opening a bug report anywhere; frivolous reports of non-bugs are mildly annoying at best and rage-inducing at worst (depending on how your day has been :). I can’t perceive why the test failed. You already diagnosed it: it was trying to run Python2-only code on Python3. Also, please try to avoid sending mail to this (or any) list in HTML or rich text format. Plain text is far easier for everyone else to deal with, from being able to actually read your message to being able to reply without having to reformat your entire message. Your client (which appears to be Outlook?) does at least include a plain text version with the HTML, but here's how it looks: https://mail.python.org/pipermail/tutor/2014-November/103477.html Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!
Forwarding my original to the list, as I failed earlier On Fri, Oct 10, 2014 at 11:34 PM, boB Stepp robertvst...@gmail.com wrote: I can live with 2.7.8 being the default Python, but if I wanted to make 3.4.2 the default, how would I go about doing it? Check the output of ftype Python.File, it should be: C:\ftype Python.File Python.File=C:\Windows\py.exe %1 %* If it's not, make it so :). Then configure the Python Launcher (py.exe) as described here: https://docs.python.org/3/using/windows.html#customization (You'll probably want your py.ini to look like this: [defaults] python=3 ) Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!
On Sat, Oct 11, 2014 at 12:30 AM, boB Stepp robertvst...@gmail.com wrote: On Sat, Oct 11, 2014 at 12:24 AM, boB Stepp robertvst...@gmail.com wrote: Cannot locate either of the mentioned py.ini files. I did a search for these on my PC and came up empty. I am going to try to create my own py.ini file and place it in C:\WINDOWS and see what happens. Correct, those files don't exist by default; they only exist if you want to change the launcher's defaults. This did the trick! Many thanks, Zach! Glad I could help :) -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to Python - print function - invalid syntax
On Tue, Aug 5, 2014 at 9:56 AM, Marc Tompkins marc.tompk...@gmail.com wrote: On Tue, Aug 5, 2014 at 12:48 AM, Maxime Steisel maximestei...@gmail.com wrote: I think this is because on windows, *.py files are associated with py.exe that choose the python version depending on the first line of your file. No. *ix operating systems (Unix, Linux, OS X, etc.) inspect the first line of a file to determine how to handle it; Windows does NOT. Have a look at PEP 397[1]. You are correct, *Windows* does not look at the shebang line. However, Maxime is also correct in that Python 3.3+ installs the Python Launcher for Windows (py.exe) and associates the .py extension with it, and *py.exe* does shebang line handling, spawning the interpreter requested by the shebang line as a subprocess. Windows simply looks at the filename extension (.py, .pyw, etc.) and consults its internal registry of file type associations. The way that you, as a user, can edit those associations has changed over the years; in Windows 7 and 8, it's Control Panel\All Control Panel Items\Default Programs\Set Associations. On the other hand, when you start up CMD.EXE and type python at the prompt, Windows uses a procedure that goes back to DOS 2 or so: the PATH environment variable. This is similar to, but a little different from, the way that *ixes work; Windows first compares what you've typed with the list of commands built-in to CMD, then with all of the executable files in the current working directory, THEN walks through the directories listed in PATH. The first matching command or executable it finds is the one that runs. Putting #!python3 on the first line of game_over2.py should solve it. NO. #! has no effect in Windows, because the choice of Python interpreter has already been made by the time anybody gets round to reading the first line of the file. #!python3.4 or #!C:\Python34\python.exe or #!/usr/bin/env python3 should all work if the '.py' extension is properly associated with the py.exe launcher, which it should be if the most recently installed Python was 3.3 or 3.4, installed with default options. -- Zach [1] http://legacy.python.org/dev/peps/pep-0397/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] conditional execution
Hi Patti, On Tue, Apr 1, 2014 at 11:07 AM, Patti Scott pscott...@yahoo.com wrote: I've been cheating: comment out the conditional statement and adjust the indents. But, how do I make my program run with if __name__ == 'main': main() at the end? I thought I understood the idea to run a module called directly but not a module imported. My program isn't running, though. The simple fix to get you going is to change your ``if __name__ == 'main':`` statement to ``if __name__ == '__main__':`` (add two underscores on each side of main). To debug this for yourself, try putting ``print(__name__)`` right before your ``if __name__ ...`` line, and see what is printed when you run it in different ways. Hope this helps, and if you need any more help or a more in-depth explanation of what's going on, please don't hesitate to ask :) Regards, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do i delete the questions that i asked and it has been shared in web
On Wed, Mar 12, 2014 at 12:46 PM, S Tareq stare...@yahoo.com wrote: this one http://code.activestate.com/lists/python-tutor/99408/ and there are other ones as well This is a mailing list. Once an email is sent, you can't unsend it. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regular expression - I
Hi Santosh, On Tue, Feb 18, 2014 at 9:52 AM, Santosh Kumar rhce@gmail.com wrote: Hi All, If you notice the below example, case I is working as expected. Case I: In [41]: string = H*testH* In [42]: re.match('H\*',string).group() Out[42]: 'H*' But why is the raw string 'r' not working as expected ? Case II: In [43]: re.match(r'H*',string).group() --- AttributeErrorTraceback (most recent call last) ipython-input-43-d66b47f01f1c in module() 1 re.match(r'H*',string).group() AttributeError: 'NoneType' object has no attribute 'group' In [44]: re.match(r'H*',string) It is working as expected, but you're not expecting the right thing ;). Raw strings don't escape anything, they just prevent backslash escapes from expanding. Case I works because \* is not a special character to Python (like \n or \t), so it leaves the backslash in place: 'H\*' 'H\*' The equivalent raw string is exactly the same in this case: r'H\*' 'H\*' The raw string you provided doesn't have the backslash, and Python will not add backslashes for you: r'H*' 'H*' The purpose of raw strings is to prevent Python from recognizing backslash escapes. For example: path = 'C:\temp\new\dir' # Windows paths are notorious... path # it looks mostly ok... [1] 'C:\temp\new\\dir' print(path) # until you try to use it C: emp ew\dir path = r'C:\temp\new\dir' # now try a raw string path # Now it looks like it's stuffed full of backslashes [2] 'C:\\temp\\new\\dir' print(path) # but it works properly! C:\temp\new\dir [1] Count the backslashes in the repr of 'path'. Notice that there is only one before the 't' and the 'n', but two before the 'd'. \d is not a special character, so Python didn't do anything to it. There are two backslashes in the repr of \d, because that's the only way to distinguish a real backslash; the \t and \n are actually the TAB and LINE FEED characters, as seen when printing 'path'. [2] Because they are all real backslashes now, so they have to be shown escaped (\\) in the repr. In your regex, since you're looking for, literally, H*, you'll need to backslash escape the * since it is a special character *in regular expressions*. To avoid having to keep track of what's special to Python as well as regular expressions, you'll need to make sure the backslash itself is escaped, to make sure the regex sees \*, and the easiest way to do that is a raw string: re.match(r'H\*', string).group() 'H*' I hope this makes some amount of sense; I've had to write it up piecemeal and will never get it posted at all if I don't go ahead and post :). If you still have questions, I'm happy to try again. You may also want to have a look at the Regex HowTo in the Python docs: http://docs.python.org/3/howto/regex.html Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regular expression - I
On Tue, Feb 18, 2014 at 11:39 AM, Zachary Ware zachary.ware+py...@gmail.com wrote: snip 'H\*' 'H\*' The equivalent raw string is exactly the same in this case: r'H\*' 'H\*' Oops, I mistyped both of these. The repr should be 'H\\*' in both cases. Sorry for the confusion! -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] could please convert this code to 3.X by using 2to3
On Tue, Feb 18, 2014 at 12:18 PM, S Tareq stare...@yahoo.com wrote: i am to convert coding to python 3.X. and some one told me to use 2to3 program but i don't how to use 2to3 program i was reading and followed the rules in python website ( http://docs.python.org/3/library/2to3.html?highlight=2to3#module-lib2to3 ) but it says error and don't work. is there any other way to convert. the original coding is used 2.7 python version. can you please help to convert this in any way. **sorry for bad English** this is the coding: snip code A few general points to try to help you: - Don't spam the same question in several different threads, and especially don't privately email list participants with the same question. Doing so is likely to get you ignored by people who would otherwise be quite happy to help you. - Don't ask people on this list to do something for you. We're here to teach, not do. - When you have an error, post the exact error, in context. If it's a shell (including Windows Command Prompt) error, give the command line you tried. If it's a Python traceback, give the whole traceback. Don't try to retype the error, copy and paste it. If you're on Windows and can't copy from the Command Prompt, use Mark from the right click menu, and press Enter when you have highlighted what you want to copy. Without knowing what the error is, it says error and don't work could mean any number of things. - Try reading this: http://docs.python.org/3/howto/pyporting.html#use-2to3 - Keep in mind that there are some things that the 2to3 tool can't convert, and so you may have to do some editing before or after conversion, or both. - Post in plain text, not HTML. Some responders here don't get the message at all if it includes HTML, and it's annoying to several others. We try to be friendly around here, but sometimes the most friendliness we (individually) can muster is to ignore posts that annoy us. Help us help you, and we'll be happy to teach you whatever you need to know! -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner - explaining 'Flip a coin' bug
Hi Marc, On Wed, Feb 12, 2014 at 9:25 AM, Marc Eymard marc_eym...@hotmail.com wrote: Hello there, I want to emulate a coin flip and count how many heads and tails when flipping it a hundred times. I first coded coinflip_WRONG.py with count_flips += 1 statement within the if/else block. When running it, either returned values are wrong or the script seems to enter in an infinite loop showing no return values at all. coinflip.py is a corrected version I worked out myself. I moved count_flips+= 1 out of if/else block and inserted it before if/else. However, I still don't understand the bug since, in my understanding, both files are incrementing variable count_flips each time until the loop becomes false. Can somebody explain the reason of the bug. The problem is that conflip_WRONG.py isn't doing what you think it's doing :). In particular, lines 23 and 24: else: count_tails += 1 count_flips += 1 While including a statement on the same line after else: is legal, it restricts you to only one statement in the block. So if we move that statement off of that line and into the block, we have this: else: count_tails += 1 count_flips += 1 I think you may be able to see what's going on from here, but to spell it out: instead of being executed in the else block, count_flips +=1 is being executed unconditionally. Since there's also a count_flips += 1 in the if coin_side == 1 block, count_flips is incremented twice when coin_side == 1, and once otherwise. Since your loop condition is coin_flips != 100, when you reach the point of coin_flips == 99 and coin_side comes up 1, coin_flips will be incremented to 101, and the loop condition will still be satisfied--hence your infinite loop. Having count_flips += 1 outside the if/else construct is better code, since you want it to be done exactly once each time through the loop no matter what, and reduces repetition. There are several other ways to improve your code as well, but they'll come with experience (or from asking :)). Hope this helps, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subtyping builtin type
On Tue, Dec 31, 2013 at 8:35 AM, spir denis.s...@gmail.com wrote: Hello, I don't remember exactly how to do that. As an example: class Source (str): __slots__ = ['i', 'n'] def __init__ (self, string): self.i = 0 # current matching index in source self.n = len(string)# number of ucodes (Unicode code points) #~ str.__init__(self, string) I thought I needed to call str's __init__, as in the line comented out, but (1) python refuses with a TypeError (2) all seems to work fine (meaning, the string is well stored, *implicitely*). Am I missing some point, or is this the way to do? How does it work? I particular, how does python know which param to take as source string? (There could be other params to __init__.) class Source(str): ... __slots__ = ['i', 'n'] ... def __init__(self, string): ... self.i = 0 ... self.n = len(string) ... s = Source('testing') s 'testing' s.i 0 s.n 7 If you look at the repr of str.__init__, you'll see that it is inherited from object: str.__init__ slot wrapper '__init__' of 'object' objects str.__init__ is object.__init__ True Compare this to the __init__ of list, which is a mutable type: list.__init__ slot wrapper '__init__' of 'list' objects list.__init__ is not object.__init__ True Being immutable, str uses __new__ to create a new str object; it doesn't use __init__ at all. Since you're not overriding __new__ in your subclass, you don't need to worry about calling str.__new__ because it's already done by the time Source.__init__ is called. HTH, -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subtyping builtin type
On Tue, Dec 31, 2013 at 9:22 AM, spir denis.s...@gmail.com wrote: Thank you, Oscar Zachary. I guess thus the way it is done is correct (for my case), is it? Seems your last remark shows the source of my confusion: probably, in past times, I subtyped builtin types and overrided their __new__, thus had to call the original one. Would I have to do this if Source had other __init__ params? Or would it work anyway provided the string remains 1st param? Or what else? The interactive interpreter is great for this kind of thing, you know ;). I didn't know the answer to this question right off, so here's what I tried: class Source(str): ... __slots__ = ['i', 'n', 'a', 'k'] ... def __init__(self, *args, **kwargs): ... self.i = 0 ... self.n = len(self) ... self.a = args ... self.k = kwargs ... s = Source('testing') s 'testing' s.i 0 s.n 7 s.a ('testing',) s.k {} s = Source('testing', 'tester', b='kwarg test') Traceback (most recent call last): File interactive input, line 1, in module TypeError: 'b' is an invalid keyword argument for this function s = Source('testing', 'tester') Traceback (most recent call last): File interactive input, line 1, in module TypeError: decoding str is not supported So it seems the answer is: if you want Source to be able to take args that str doesn't, you'll have to define __new__ and intercept the arguments you want (or the arguments meant for str) and pass only str's arguments to str.__new__ to get self. Depending on what you're trying to do, it may turn out easier (and less confusing) to not subclass str at all, and just keep a _string attribute for the string. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subtyping builtin type
On Tue, Dec 31, 2013 at 10:21 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: The glossary entry for __slots__ states A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application. I'll admit that I really don't understand what's tricky about it, can someone explain please. I'm not sure, exactly. My suspicion is that it can be rather annoying to make sure you don't add just one extra attribute that isn't in __slots__ (yet), or to make sure that you found every attribute you ever access or might need to access in every branch of every method of everything that uses the class or an instance thereof (since using __slots__ means you can't add anything to the class dynamically, unless you add __dict__ to __slots__ which defeats half the purpose). Also, it's probably meant to add just a faint touch of FUD since it really isn't necessary 95+% of the time, especially for newbies. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subtyping builtin type
On Tue, Dec 31, 2013 at 11:53 AM, eryksun eryk...@gmail.com wrote: Minor correction: It says str requires empty __slots__, but that's a bug in the docs. It's referring to 2.x str. Else this thread wouldn't exist. In 3.x, str is basically the unicode type from 2.x. Its __itemsize__ is 0 because the character array is allocated separately. Actually in CPython 3.3 there's a compact string object (i.e. PyCompactUnicodeObject), but that's not used for a subclass. Appending new slots to an instance poses no problem for a subclass of str. It is still true for bytes objects, though. Thanks for pointing that out, it is now fixed. Regarding __class__ assignment, I'll add that it also breaks if the types include a __dict__ or __weakref__ slot in addition to other slots. For example, this works fine: class C: __slots__ = '__weakref__', class D: __slots__ = '__weakref__', C().__class__ = D But adding another slot pushes __weakref__ out of its expected position in the layout, so the test for a compatible layout fails: class C: __slots__ = '__weakref__', 'a' class D: __slots__ = '__weakref__', 'a' C().__class__ = D Traceback (most recent call last): File stdin, line 1, in module TypeError: __class__ assignment: 'C' object layout differs from 'D' The layout is identical, but the test it uses can't see that. Would you mind opening an issue for this? This looks like it may be fixable (or the doc should be updated). -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
On Tue, Dec 17, 2013 at 10:37 AM, Wolfgang Maier wolfgang.ma...@biologie.uni-freiburg.de wrote: Peter Otten __peter__ at web.de writes: Look at this line: if __name__ == __main__: do so very closely :) In monospaced font :) Took me forever to see it, thanks Gmail... -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unstring
Jim Mooney cybervigila...@gmail.com wrote: Is there a way to unstring something? That is str(object) will give me a string, but what if I want the original object back, for some purpose, without a lot of foofaraw? Only by keeping the original reference to the object. str(object) produces a new object that has absolutely no relation to the original. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue with string method: str(variable ** n)
On Thu, May 16, 2013 at 1:58 PM, Rafael Knuth rafael.kn...@gmail.com wrote: Hej, Hi Rafael, I wrote a tiny little program which I was hoping would take a number as input, square and print it: square = input (Enter a number. ) print (str(square) + squared is + str(square ** 2)) It seems I can't work with variables within the str() string method, and I was wondering if anyone can help? PS. I am using Python 3.3.0 In the future, it's always very helpful to post any tracebacks you get, everything from Traceback (most recent call last): to the last thing printed. In this case, it seems that your problem is that in Python3, input() returns the input as a string. Python2's input() function would actually evaluate the input, which was incredibly insecure. You can fix your program by calling int() on square at the end of your print call. If I were writing this myself, I would do this, though: number = int(input(Enter a number. )) print({} squared is {}.format(number, number**2)) You might find the tutorial page on Input and Output[1] instructive, particularly about the format method I used above. Hope this helps, Zach [1] http://docs.python.org/3/tutorial/inputoutput.html Thank you in advance! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] stumped by what looks like recursive list comprehension
On Sun, May 5, 2013 at 11:56 AM, Jim Mooney cybervigila...@gmail.com wrote: I looked up list comprehension after the last explanation and it's really cool. But the example below stumps me. I understand the second part, primes = but the first part, noprimes = baffles me since it swaps i and j back and forth in what looks like a circle ;') Also, the other examples I looked at had a function of 'x' before the 'for,' and 'x' after, so they were easy to follow. But this example has 'j' as a function of 'i,' then 'i,' as a function of 'j' and has me dizzy. Could someone show this in normal, indented 'for' loops so I can see what 'for' goes where and how it works. I figure if I figure this one one I'll really comprehend list comprehension. # find nonprimes up to 50, then filter out what's left as primes noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes] The standard expansion of a list comprehension is as follows: noprimes = [] # start with an empty list for i in range(2,8):# add a colon, a newline, and another indention for j in range(i*2, 50, i): # level just before each 'for' and 'if' noprimes.append(j)# everything before the first 'for' goes in an # append call on the empty list primes = [] for x in range(2, 50): if x not in noprimes: primes.append(x) Hope this helps, Zach Ware -- Jim Mooney “For anything that matters, the timing is never quite right, the resources are always a little short, and the people who affect the outcome are always ambivalent.” ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] exit message
On Sun, May 5, 2013 at 11:24 PM, Jim Mooney cybervigila...@gmail.com wrote: I've noticed that if you exit() a program you always get a traceback message: Traceback (most recent call last): File pyshell#1, line 1, in module exit('what now?') File C:\Python33\lib\site.py, line 380, in __call__ raise SystemExit(code) What if you just want to exit for some normal reason and don't want the message? Or is a program always supposed to end in some normal way without an exit. Or is there a different, more graceful way to end a program when you want? I believe that traceback is a bug in IDLE, which I think has been fixed for the next release (or is being chased, one of the two). If you're not using IDLE, it's another bug that should be tracked down :). More generally, though, you can't count on 'exit()' being available. exit() is made available by the 'site' module (as you can see in the traceback), but if Python is run with the -S option, 'site' won't be imported and 'exit()' won't be available. Instead, you can do what exit() actually does, which is to raise the SystemExit exception with the code to be returned to the shell. For instance (and be warned that I'm typing this from a Linux box, so it's untested, but you should be able to reproduce this :)): C:\py type example.py # example.py print('Hello') raise SystemExit(13) print('Goodbye') C:\py py -3.3 example.py Hello C:\py echo %ERRORLEVEL% 13 You can also import sys and use sys.exit() for the same effect. If you don't care about the exit code, you can just drop off the end of the script. If you don't end with an unhandled exception, your exit code will be 0, otherwise it will (probably) be 1. For example: # example2.py def main(arg=None): print('This is a main function. It's not special, you still have to call it.') if arg: return raise ValueError('If you had supplied an argument, you wouldn't get this message') if __name__ == '__main__': import sys if len(sys.argv) 1: main(sys.argv[1]) else: main() Hope this helps, Zach Ware ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor