Re: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
On Wed, Jul 06, 2016 at 03:35:16PM -0400, bruce wrote: > Hi. > > Saw the decorator thread earlier.. didn't want to pollute it. I know, > I could google! > > But, what are decorators, why are decorators? who decided you needed > them! Sometimes you find yourself writing many functions (or methods) that have bits in common. For example, you might have a bunch of mathematical functions that all start off with the same boring code "check that the argument x is a number, raise an exception if it isn't". Sure, it's only two or three lines, but if you've got twenty functions to write, you have to write those same lines twenty times. And then if you decide to change the error message, or change the way you check something is a number, you have to do that in twenty places. A decorator let's you factor out that common code into a single place, so you only need to make changes to *one* place instead of twenty separate functions. You still have to apply the decorator to each of the functions, but that's only once line. Besides, a decorator is not really about cutting back the number of lines of code (although it is nice when that happens) as it is about moving common code to one place. def verify_numeric_argument(func): """Decorator that checks the argument to a function is a number.""" @functools.wraps(func) def inner(x): if isinstance(x, numbers.Number): return func(x) else: kind = type(x).__name__ raise TypeError("expected a number, but got %s" % kind) return inner @verify_numeric_argument def sinc(x): if x == 0: return 1.0 else: return math.sin(x)/x Obviously you wouldn't bother if you're only going to do it *once*. There's a bunch of overhead involved in writing a decorator, usually about five or six lines of code per decorator. The rule of thumb I use is that if I have one or two functions with the same, common, chunk of code, I probably wouldn't bother; if I have three functions, I might, and if I have four or more, then I probably will. But as I said, it's not really about saving lines of code. It's about keeping code that belongs together in one place, and about recognising when functions repeat the same structure. If you have a bunch of functions that look like this: def function(arguments): boring boilerplate that is the same each time interesting bit that is different each time more boring boilingplate return result then this is a great candidate for a decorator: move the boring boilerplate into the decorator, then turn the functions into this: @apply_boilerplate def function(arguments): interesting bit that is different each time return result Doesn't that look better? That's the purpose of the decorator: move the boring bits, or sometimes the hard, complicated bits, away so you can focus on the interesting bits. Depending on just how boring that boilerplate is, I might even do it for ONE function, just to get it out of the way. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] error
> > Have you checked that you have the requisite permissions? That the > socket you are connecting to exists? If its a system call error the > problem is most likely in your environment rather than your code. > That particular error is from Windows. One common cause for it is a network firewall, which normally is great because at least it's working as a first line of defense. If that's the case, you probably want to tell your firewall to make an exception for your program. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
> As to who suggested them you'd need to go back through the > PEPs to see who first suggested it, and then maybe more to see > who's idea finally got accepted. I think it was in Python 2.5. Hi Bruce, Yes, it happened back around 2003: https://www.python.org/dev/peps/pep-0318/ Decorators are "syntactic sugar" in the sense that they can be rewritten in terms of more primitive parts of the language (function calls). If you already know about functions that work on functions, then you know what decorators are. However, if you haven't seen the concept of functions that take functions as input, and you want to talk about that, feel free to ask questions! It would likely be a "fun" discussion to have. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OS and Windows version
On 06/07/16 19:34, Moses, Samuel wrote: > Mine > > OS: Windows > Windows version: 8.1 > > Python 3.2 > Wing IDE: 15.1 Thanks for the extra info but it doesn't help much with your problem since we still don't know what your code does nor how your environment is set up. BTW Can you connect to your target socket using telnet? (Use a CMD console)If you get an error message there you probably can't connect from Python either. Finally you could try running the script outside Wing. IDEs can do all sorts of weird stuff to programs. Its always worth a try running it using the vanilla Python interpreter. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
On 06/07/16 20:35, bruce wrote: > Saw the decorator thread earlier.. didn't want to pollute it. I know, I > could google! > > But, what are decorators, why are decorators? who decided you needed them! decorators are things that modify functions in standard ways. Specifically they are functions that act on functions. Mostly people think of them as being the thing that comes after an @ sign, but in fact they are just functions but with a bit of syntactic sugar to make them more readable. You don't really *need* them as a feature, but if you have the ability to treat functions as values they are a useful technique. Most Python programmers don't implement decorators they just use the standard ones. But as the thread showed implementing them is not too difficult once you get happy with the idea of passing functions around as arguments to other functions. As to who suggested them you'd need to go back through the PEPs to see who first suggested it, and then maybe more to see who's idea finally got accepted. I think it was in Python 2.5. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
On Wed, Jul 6, 2016 at 4:56 PM, Alex Hallwrote: > > > On Wed, Jul 6, 2016 at 3:35 PM, bruce wrote: > >> Hi. >> >> Saw the decorator thread earlier.. didn't want to pollute it. I know, I >> could google! >> >> But, what are decorators, why are decorators? who decided you needed them! >> > > I thought of an example that may help. It's not a great example, but here goes. Say you own a bakery, and you employ Joe and me. You task me with taking cookies from the kitchen and putting them in the display case in the service area, which I do well. The problem is that I don't know what looks appealing and what doesn't, so I keep putting cookies out that don't look great. You can't teach something like that, it's just something you know. Since you can't modify me to do my task in the way you want, you grab Joe and have him help me. Instead of putting all the cookies out, I now have Joe checking me before I place each one. Joe knows appealing, so is good at this, but he's also usually busy up front so can't carry the cookies out from the kitchen like I can. Joe is the decorator, and I'm the function being decorated. Since I do my task well, but lack a component you want, and since that component would be hard to program, you find an existing version of the component (Joe) and tell us to work together. Joe can modify my output before I return it, letting him filter the appealing cookies out while I do the work of carrying them up and setting out the ones Joe doesn't tell me to reject. Hopefully this makes some sense. > They're functions that modify the decorated function. If I make a function > that performs a task, I might decorate with a logging function: > > @logThis > def doSomething(): > #do stuff > > The logThis decorator could log the run, or modify the doSomething output, > or do any number of tasks. To get that extra functionality, I need only > decorate my own function. I see these a lot in Flask, a web framework, > where they are used to define what parts of your website are handled by > what functions, for instance. Basically, they let you extend what your > functions do without needing to subclass anything. > >> >> Thanks! >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Alex Hall > Automatic Distributors, IT department > ah...@autodist.com > -- Alex Hall Automatic Distributors, IT department ah...@autodist.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OS and Windows version
Mine OS: Windows Windows version: 8.1 Python 3.2 Wing IDE: 15.1 Sam ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
On Wed, Jul 6, 2016 at 3:35 PM, brucewrote: > Hi. > > Saw the decorator thread earlier.. didn't want to pollute it. I know, I > could google! > > But, what are decorators, why are decorators? who decided you needed them! > They're functions that modify the decorated function. If I make a function that performs a task, I might decorate with a logging function: @logThis def doSomething(): #do stuff The logThis decorator could log the run, or modify the doSomething output, or do any number of tasks. To get that extra functionality, I need only decorate my own function. I see these a lot in Flask, a web framework, where they are used to define what parts of your website are handled by what functions, for instance. Basically, they let you extend what your functions do without needing to subclass anything. > > Thanks! > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Alex Hall Automatic Distributors, IT department ah...@autodist.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] decorators -- treat me like i'm 6.. what are they.. why are they?
Hi. Saw the decorator thread earlier.. didn't want to pollute it. I know, I could google! But, what are decorators, why are decorators? who decided you needed them! Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] error
On 06/07/16 18:27, Moses, Samuel wrote: > I am getting an error. I tired to run the script in wing IDE. > Without the accompanying code we can only guess. > I am getting this error, > > "Traceback (most recent call last): > File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in > main > args['firststop'], err, netserver, pwfile_path) > File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in > CreateServer > pwfile_path, internal_modules=tuple(internal_modules)) > File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in > __init__ > File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in > __PrepareConnectListener > File "C:\Python32\lib\socket.py", line 94, in __init__ > _socket.socket.__init__(self, family, type, proto, fileno) > socket.error: [Errno 10107] A system call has failed" Have you checked that you have the requisite permissions? That the socket you are connecting to exists? If its a system call error the problem is most likely in your environment rather than your code. But check the values you pass into socket. Print them out to check they are what you (and Python) expect... > I tried printing "Christmas" I have no idea what that means. Literally putting print "Christmas" in your code probably wouldn't help so I assume you did something else? > It said there was no TCP/IP connection. What said? Was it another error trace? Or something else? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
On 06/07/16 15:04, loh...@tuta.io wrote: > script, filename = argv > txt = open (filename) > > print "Here's your file %r: " % filename > print txt.read() > > print "Type the filename again: " > file_again = raw_input("> ") > > txt_again = open(file_again) > print txt_again.read() > why do I have to create a variable txt_again to assign it to the open > function and them print the file? You don't, and could get away with a single variable - filename. Like this: filename = argv[1] print "Here's your file %r: " % filename print open(filename).read() filename = raw_input("Type the filename again: >") print open(filename).read() But your book is (I assume) trying to teach you good practice. While you could have just printed the result of read directly, its better not to over complicate code by doing too much in one line (for a start, its harder to debug) the same variable. Variables are cheap to create and if given useful names tell us a lot about the purpose of the code. In this case it's all a bit trivial, just printing the file content, but if you were doing more complex processing storing the file (and data) in variables would be the best choice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Subclassing logging.Handler?
On Wed, Jul 6, 2016 at 1:01 PM, Alex Hallwrote: > Regarding this project: I've gone ahead and tried a variant of it. I > wanted to log to an HTML file, since those are much easier to look at with > a screen reader and so I could get used to the concepts involved. Here's > what I've come up with so far. I'll ask the question, then paste the code. > I'm getting an error on the self.stream.write line in _open that > "'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm > subclassing TimedRotatingFileHandler, how can it not have stream? > Again, in case someone is searching for an answer later and finds this thread: you must assign it. def _open(self): self.stream = super(ADTimedRotatingLogFileHandler, self)._open() I'm now getting a different error, in close(): TypeError: must be type, not None I'm not sure what that's about, but at least I now know why I wasn't getting a stream. > > import logging > import logging.handlers as logHandlers > class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler): > > def __init__(self, filename, when, interval, backupCount, title): > """Most parameters are for the superclass, but 'title' is the > title you want your HTML file to have.""" > super(ADTimedRotatingLogFileHandler, self).__init__(filename, > when, interval, backupCount) > self._title = title > > def _open(self): > super(ADTimedRotatingLogFileHandler, self)._open() > self.stream.write(""" > > %s > > > """ %(self._title)) > > def close(self): > self.stream.write(""" > > """) > super(ADTimedRotatingLogFileHandler, self).close() > > > On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall wrote: > >> Hey list, >> Another day, another Python experiment. I'm wondering what methods I'd >> have to implement in a custom subclass of logger.Handler. >> >> Currently, the recurring jobs I have written log their events to a file >> each time they run. That's fine, but it doesn't let me keep >> easily-sorted/searched records. Even if I use a size-based log file >> handler, it'll get hard to search. I'm pondering logging to a database as >> well, so that the files will always have the most recent few runs, but the >> database will have everything. That means subclassing logger.Handler. >> >> I found the docs for this, but is emit() the only function I need to >> implement? There are things about i/o locks, formatting, and so on as well. >> How much do I need to do, and how much can I leave up to the super class? >> I'll have to call >> super(MyLogHandler, self).__init__() >> I know, but what else do I have to worry about? To be clear, I'm not >> asking about logging to a database, only what to do to make a Handler >> subclass capable of logging through whatever mechanisms I want. Thanks. >> >> -- >> Alex Hall >> Automatic Distributors, IT department >> ah...@autodist.com >> > > > > -- > Alex Hall > Automatic Distributors, IT department > ah...@autodist.com > -- Alex Hall Automatic Distributors, IT department ah...@autodist.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] error
I am getting an error. I tired to run the script in wing IDE. I am getting this error, "Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in main args['firststop'], err, netserver, pwfile_path) File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in CreateServer pwfile_path, internal_modules=tuple(internal_modules)) File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in __init__ File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in __PrepareConnectListener File "C:\Python32\lib\socket.py", line 94, in __init__ _socket.socket.__init__(self, family, type, proto, fileno) socket.error: [Errno 10107] A system call has failed" I tried printing "Christmas" It said there was no TCP/IP connection. Any suggestion would help Thank you Samuel Moses ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
On Wed, Jul 6, 2016 at 10:59 AMwrote: > why do I have to create a variable txt_again to assign it to the open > function and them print the file? > why is it that I can't only write something like open(file_again).read()? > Good insight. In fact you don't need to create the variable. The code ``data = open('filename').read()`` will open the file named "filename" in the current working directory, read it, and assign the data to a variable. However, many programmers use variables not because they must, but because good variable names can make code easier to read. Also, doing less stuff on a line of code can make that code easier to read. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Subclassing logging.Handler?
Regarding this project: I've gone ahead and tried a variant of it. I wanted to log to an HTML file, since those are much easier to look at with a screen reader and so I could get used to the concepts involved. Here's what I've come up with so far. I'll ask the question, then paste the code. I'm getting an error on the self.stream.write line in _open that "'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm subclassing TimedRotatingFileHandler, how can it not have stream? import logging import logging.handlers as logHandlers class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler): def __init__(self, filename, when, interval, backupCount, title): """Most parameters are for the superclass, but 'title' is the title you want your HTML file to have.""" super(ADTimedRotatingLogFileHandler, self).__init__(filename, when, interval, backupCount) self._title = title def _open(self): super(ADTimedRotatingLogFileHandler, self)._open() self.stream.write(""" %s """ %(self._title)) def close(self): self.stream.write(""" """) super(ADTimedRotatingLogFileHandler, self).close() On Wed, Jul 6, 2016 at 8:32 AM, Alex Hallwrote: > Hey list, > Another day, another Python experiment. I'm wondering what methods I'd > have to implement in a custom subclass of logger.Handler. > > Currently, the recurring jobs I have written log their events to a file > each time they run. That's fine, but it doesn't let me keep > easily-sorted/searched records. Even if I use a size-based log file > handler, it'll get hard to search. I'm pondering logging to a database as > well, so that the files will always have the most recent few runs, but the > database will have everything. That means subclassing logger.Handler. > > I found the docs for this, but is emit() the only function I need to > implement? There are things about i/o locks, formatting, and so on as well. > How much do I need to do, and how much can I leave up to the super class? > I'll have to call > super(MyLogHandler, self).__init__() > I know, but what else do I have to worry about? To be clear, I'm not > asking about logging to a database, only what to do to make a Handler > subclass capable of logging through whatever mechanisms I want. Thanks. > > -- > Alex Hall > Automatic Distributors, IT department > ah...@autodist.com > -- Alex Hall Automatic Distributors, IT department ah...@autodist.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Subclassing logging.Handler?
Hey list, Another day, another Python experiment. I'm wondering what methods I'd have to implement in a custom subclass of logger.Handler. Currently, the recurring jobs I have written log their events to a file each time they run. That's fine, but it doesn't let me keep easily-sorted/searched records. Even if I use a size-based log file handler, it'll get hard to search. I'm pondering logging to a database as well, so that the files will always have the most recent few runs, but the database will have everything. That means subclassing logger.Handler. I found the docs for this, but is emit() the only function I need to implement? There are things about i/o locks, formatting, and so on as well. How much do I need to do, and how much can I leave up to the super class? I'll have to call super(MyLogHandler, self).__init__() I know, but what else do I have to worry about? To be clear, I'm not asking about logging to a database, only what to do to make a Handler subclass capable of logging through whatever mechanisms I want. Thanks. -- Alex Hall Automatic Distributors, IT department ah...@autodist.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
first, sorry everyone for having attached the file instead of just typing it here. second, thanks a lot for the replies; even though I gave you no code it was quite helpful! the code was this: from sys import argv script, filename = argv txt = open (filename) print "Here's your file %r: " % filename print txt.read() print "Type the filename again: " file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() Peter Otten explained it to me line by line [thanks so much :)] however, I do have one more question: why do I have to create a variable txt_again to assign it to the open function and them print the file? why is it that I can't only write something like open(file_again).read()? 6. Jul 2016 05:22 by __pete...@web.de: > loh...@tuta.io> wrote: > >> hey everyone. this is my first time trying this -- actually, I've been >> studying python only for some days now, and I'm afraid my questions are >> going to be rally simple, but I can't seem to understand this piece of >> code and thus can't move on. > > You seem to be talking about > > http://learnpythonthehardway.org/book/ex15.html > > """ > from sys import argv > > script, filename = argv > > txt = open(filename) > > print "Here's your file %r:" % filename > print txt.read() > > print "Type the filename again:" > file_again = raw_input("> ") > > txt_again = open(file_again) > > print txt_again.read() > """ > > As others said, always provide the code you are asking about, or if that is > not possible at least provide a link. > >> you probably know the book, so you know that zed always makes us write >> code so that then we can understand how it works, and it's great, but in >> this exercise there are just too many new functions and without >> explanation they are a bit hard to understand... so I'm having trouble >> with most of the lines here. >> >> it's not that I want the full explanation to that code, but since I'm >> unfamiliar with some of its concepts, I'm just going to tell you all the >> things that I don't understand (sorry for it being a lot): >> 1. the need to put script into an estipulation for argv (line 3) > > Write a script tmp.py containing > > from sys import argv > print argv > > then call it with with one parameter, e. g. > > $ python tmp.py somefile.txt > ['tmp.py', 'somefile.txt'] > > As you can see argv is a list with two items, the first being "tmp.py", the > name of the script you are invoking. You are only interested in the second > one, the filename. The easy way to get that is > > filename = argv[1] > > the hard way is to use "unpacking" > > script, filename = argv > > where python will assign one item from the list on the right to every name > on the left: > items = ["foo", "bar"] one, two = items one > 'foo' two > 'bar' > > What happens if the number of names on the left doesn't match the number of > items in the list? > one, two, three = items > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 2 values to unpack > > You get an exception. That is why you have to provide the name "script" in > Zed's example even though you are not actually interested in the script > name. > >> 2. the what is txt and why it has to be used there (line 4) > > txt is a file object and > >> 3. txt.read() -- which are all new functions(? I dont even know what they >> are) (line 7) > > read() is a method that here reads the whole file into a string. You use > the > open() function to open a file and usually assign the file object that is > returned by open to a name. You can freely choose that name. The structure > is the same for every object, be it a number: > > x = 42 # assign a number to x > y = x + x # do some arithmetic with x and assign the result to y > print y # print the result > > a list: > > mynumbers = list() # create a list > mynumbers.append(42) # append a number to the list > print mynumbers # print the list > > or a file: > > myfile = open("example.txt") # open the file example.txt in the current > # working directory. If the file doesn't > exist > # you get an error > > print "first line:", myfile.readline() # read the first line and print it > print "rest of the file:" > print myfile.read() # read the rest of the file and print it > > myfile.close() # close the file > >> 4. file_again (line 10) >> 5. txt_again (line 12) >> and line 14. > > 4. and 5. are just a repetition of the first part, with the variation that > the filename, assigned to file_again is read interactively with raw_input() > instead of passing it as a commandline argument to the script. > > The names used can be freely chosen by the programmer, a script > > from sys import argv > > red_apple, my_hat = argv > > blue_suede_shoes = open(my_hat) > print blue_suede_shoes.read() > blue_suede_shoes.close() > > would work exactly like the first part of the hard-way example. However, > picking
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
loh...@tuta.io wrote: > hey everyone. this is my first time trying this -- actually, I've been > studying python only for some days now, and I'm afraid my questions are > going to be rally simple, but I can't seem to understand this piece of > code and thus can't move on. You seem to be talking about http://learnpythonthehardway.org/book/ex15.html """ from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() """ As others said, always provide the code you are asking about, or if that is not possible at least provide a link. > you probably know the book, so you know that zed always makes us write > code so that then we can understand how it works, and it's great, but in > this exercise there are just too many new functions and without > explanation they are a bit hard to understand... so I'm having trouble > with most of the lines here. > > it's not that I want the full explanation to that code, but since I'm > unfamiliar with some of its concepts, I'm just going to tell you all the > things that I don't understand (sorry for it being a lot): > 1. the need to put script into an estipulation for argv (line 3) Write a script tmp.py containing from sys import argv print argv then call it with with one parameter, e. g. $ python tmp.py somefile.txt ['tmp.py', 'somefile.txt'] As you can see argv is a list with two items, the first being "tmp.py", the name of the script you are invoking. You are only interested in the second one, the filename. The easy way to get that is filename = argv[1] the hard way is to use "unpacking" script, filename = argv where python will assign one item from the list on the right to every name on the left: >>> items = ["foo", "bar"] >>> one, two = items >>> one 'foo' >>> two 'bar' What happens if the number of names on the left doesn't match the number of items in the list? >>> one, two, three = items Traceback (most recent call last): File "", line 1, in ValueError: need more than 2 values to unpack You get an exception. That is why you have to provide the name "script" in Zed's example even though you are not actually interested in the script name. > 2. the what is txt and why it has to be used there (line 4) txt is a file object and > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) read() is a method that here reads the whole file into a string. You use the open() function to open a file and usually assign the file object that is returned by open to a name. You can freely choose that name. The structure is the same for every object, be it a number: x = 42 # assign a number to x y = x + x # do some arithmetic with x and assign the result to y print y # print the result a list: mynumbers = list() # create a list mynumbers.append(42) # append a number to the list print mynumbers # print the list or a file: myfile = open("example.txt") # open the file example.txt in the current # working directory. If the file doesn't exist # you get an error print "first line:", myfile.readline() # read the first line and print it print "rest of the file:" print myfile.read() # read the rest of the file and print it myfile.close() # close the file > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. 4. and 5. are just a repetition of the first part, with the variation that the filename, assigned to file_again is read interactively with raw_input() instead of passing it as a commandline argument to the script. The names used can be freely chosen by the programmer, a script from sys import argv red_apple, my_hat = argv blue_suede_shoes = open(my_hat) print blue_suede_shoes.read() blue_suede_shoes.close() would work exactly like the first part of the hard-way example. However, picking descriptive names and using them consistently makes it much easier for a human reader to understand what's going on. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
On 06/07/16 00:56, loh...@tuta.io wrote: > hey everyone. this is my first time trying this Welcome, but... > you probably know the book, Sorry, I don't and I suspect I'm not alone. It's probably a fine book, but we don't all know it. > so you know that zed always makes us write code > so that then we can understand how it works, Good man Zed :-) > exercise there are just too many new functions and without explanation they > are a bit hard to understand... so I'm having trouble with most of the lines > here. And here's the next problem. This is a text based mailing list. As such the server often strips out attachments as potential security risks. So we can't see the code (I'm assuming you attached it?) > 1. the need to put script into an estipulation for argv (line 3) > 2. the what is txt and why it has to be used there (line 4) > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. Without sight of the code its hard to know what's going on. But I suspect some of these "functions" are actually variables (or objects) and hopefully zed has already discussed those? Can you repost but include your code inside the mail message. Also try to post in plain text since HTML tends to get garbled in transit. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dont understand part of a code
On Tue, Jul 5, 2016 at 5:36 PM Michael Selikwrote: > On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor > wrote: > >> There are arguably easier ways of doing this >> > > I think you'll find that for-loops are preferable to while-loops. Here's > an alternative implementation. > > https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca > On further reflection, unfortunately a for-loop doesn't seem best for this particular problem. I updated the gist, linked above. I wish the author had chosen a better problem to emphasize Pythonic iteration. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with exercise 15 of zed shaw's LPTHW
On Tue, Jul 5, 2016 at 8:24 PMwrote: > I'm having trouble with most of the lines here. > It looks like you tried to attach a file. This mailing list does not allow attachments. Instead, could you paste the code into your email? > things that I don't understand: > 1. the need to put script into an estipulation for argv (line 3) > 2. the what is txt and why it has to be used there (line 4) > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) > I'm guessing txt is a file object or a file-like object that supports the .read method to read the entire contents of the file into a single string object. > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] isinstance versus 'is'?
Thanks everyone, that all makes more sense. I think I was indeed thinking of "is None", which is essentially the same as "== None" (I know there's a subtile difference, but they do the same thing). Of course, "is None" fits with this usage, as you're asking if the value is the literal None object. It seems it's the way None is handled, not an exception in the way 'is' works. Anyway, thanks for the explanations. > On Jul 5, 2016, at 20:54, Steven D'Apranowrote: > > On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote: > > a = 5 > isinstance(a, int) >> True > a is int >> False >> >> What happened there? Don't these do the same thing? I thought I could use >> them interchangeably? > > You're probably thinking of "is a", as in, "5 is an int", "'Hello > World' is a str", "[1, 2, 3] is a list", etc. > > Python doesn't have an operator for testing "is a" relationships, it > uses isinstance(obj, type). There's also issubclass(), for testing > whether one class is a subclass of another. > > "x is y" checks whether the two operands x and y are the same object. > That's *not* the same as checking whether they are equal. You should > hardly ever use "is" in Python, with the exception of testing for None: > "if obj is None: ..." sort of thing. > > > -- > Steve > ___ > 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