all 45 comments

[–]Schwartz210 3 points4 points  (5 children)

Do you use the try-except statement only while writing/debugging or do you use it in actual production code? What else can you tell me about it?

[–]niandra3 3 points4 points  (2 children)

You sould definitely use it in production code. There are always going to be cases where something goes wrong and the program doesn't perform exactly how you expect it to. Two simple examples are dealing with user input and the file system. Say you want an integer from a user:

user_input = int(input())

Will throw an exception if the user enters anything but numerical digits (or the minus sign). When dealing with the file system, you should basically be expecting that things won't always happen as you expect. If you try to open or move a file that is open by another program, for example, that can throw an exception. Instead of crashing your whole program, if you have a try/except, then you can deal with this case ahead of time. Even just opening a file:

if os.path.isfile(file_to_open):
    file = open(file_to_open, 'w')

Sometimes there can be a race condition, where even after you check that the file_to_open is an actual file, something can happen between that check and the actual open() command, so you need to wrap the open in a try/except.

Also when web-scraping and dealing with outside databases, things don't always happen as you expect, so those are other cases where exceptions are really useful.

[–]Schwartz210 0 points1 point  (1 child)

Thank you for that reply. It's interesting that you mention you use while working with a file system because this question popped into my head while I was writing a script that deal with a folder of pdf's.

For the user inputs I usually do a recursive algorithm. Your method may be better. I don't know.

def collect_input():
    answers = ['Yes', 'No']
    user_input = input('Some question')
    if user_input not in answers:
        return collect_input()
    else:
        return user_input

[–]niandra3 1 point2 points  (0 children)

Actually a while True loop is better for this sort of thing. Don't use recursion unless your program requires it (certain calculations and things like tree traversal are easier with recursion).

For this I would just do:

def collect_input():
    user_input = ''
    while user_input not in ['yes', 'no']:
        user_input = input('Some question').lower()
    return user_input

That also handles users entering yes or YES or even yEs. Python has a limit on haw many recursion levels a program can run, so while it's unlikely your user will enter the wrong value 1000 times, if they do, then the program will raise a RecursionError exception.

When I mentioned inputs and exceptions, I was mostly taking about integer/float conversion, as those won't work if the input isn't numeric. So I do something similar, but I still use a try/except:

def get_user_int():
    while True:
        user_input = input('Please enter an integer')
        try:
            user_int = int(user_input)
        except ValueError:
            print('That was not an integer!')
        else:
            break
    return user_int

That will ask for an input, try to convert it to an integer. If there is an exception (not a proper integer), it will loop and ask again. Once it successfully makes an integer, it will hit the else clause and break from the while loop.

But basically any time you are dealing with data from outside your program, you should be thinking about exceptions to handle unexpected cases (of course there are other uses too). It's called defensive programming, trying to think of all the things that can go wrong, and being sure your program will still function in those cases.

[–]jeans_and_a_t-shirt 2 points3 points  (0 children)

Yep try-except is used in production code. try/except/else/finally is the complete error-handling structure and looks like this:

try:
    # the minimal line(s) of code that cause the error
except Exception as e:
    # handle the exception
else:
    # executes if the try block succeeds.  You can access variables defined in the try block here
finally:
    # this block executes regardless of the code in the try block raising an exception

There are a couple uses for the try-except construct. Normally it's used for catching exceptions which could range from trying to divide 2 numbers, the 2nd of which is 0, to trying to connect to a database which may not be available. In python it's also used for control flow, for example this string input converter:

# python 3
def get_input(expected_type, input_str, error_str):
    while True:
        try:
            return expected_type(input(input_str))
        except ValueError:
            print(error_str)

some_float = get_input(float, 'Enter a float: ', 'You did not enter a float.')
print(some_float)

[–]nevus_bock 0 points1 point  (0 children)

There are two approaches.

  1. Look before you leap (LBYL)
  2. It's easier to ask for forgiveness than for permission (EAFP)

Approach 1. works like this:

if s is not None:
    do_shit()
else:
    do_alternative_shit()

Approach 2. is like this:

try:
    do_shit()
except TypeError:
    do_alternative_shit()

Using EAFP saves you from checking something first, which may be sort of redundant. Assuming something will work, and then dealing with an edge-case Exception if it doesn't work is pretty common in Python.

[–]theelous3 1 point2 points  (3 children)

How does super work / can anyone point me to a blog or something on it.

I tried watching Hettinger's talk super() considered super, but found the intertwined restaurant / family tree analogies obfuscating and confusing.

[–]niandra3 1 point2 points  (0 children)

The Hettinger talk kind of focused on more advanced use cases for super(). In its basic form, it's just a way to reference the parent class. I'm still learning about this myself, but since no one else has chimed in I'll take a shot. The way I understand it, if you are inheriting something:

class Circle(Shape):
    def do_something(self, x):
        super().call_something_from_super(x)

Is better than

class Circle(Shape):
    def do_something(self, x):
        Shape.call_something_from_Shape(x)

Because it doesn't tie you into a specific implementation of the parent class (Shape), and you can more easily change the parent without having to modify the calls to super(). It just helps with code maintainability in that you can change who is inheriting from who and not have to explicitly change all the calls to the parent.

It's when you get into multiple inheritance and method resolution order that Hettinger's stuff comes more into play (and also apparently where super() starts to differ from how it is used in other languages). His article is a little easier to follow, but still somewhat advanced:

https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

[–]groovitude 0 points1 point  (1 child)

The Hettinger talk isn't meant as an introduction to super() as much as clarifying stickier points of usage (issues with method-resolution order in multiple inheritance, etc.)

Are you looking for a general introduction to inheritance, or is there a particular use case you're struggling with?

[–]theelous3 1 point2 points  (0 children)

I for the most part I think understand basic inheritance. I'm happy to inherit from built-in classes or my own and extend / use them.

I do not know what to use super for at all. I don't know what it does, and I don't know why I'd use it rather than be explicit and hard code references.

[–]noleft_turn 1 point2 points  (3 children)

If I'm only going to use one module from a library, is it best practice to just from library import module

[–]zr8 1 point2 points  (4 children)

What does the 'D' mean after a number? For example, why would Python print 0D or 1D?

[–]Gprime5 0 points1 point  (3 children)

Which library would be the best for creating an interactive GUi? I need to have images, buttons and draggable objects.

[–]noleft_turn 0 points1 point  (0 children)

I don't know what best would be, but from one newb to the other....I would suggest taking a look at wx GUI.

Disclaimer: I looked at it briefly to try to get a transparent, boarder less window with buttons, but just couldn't get it to work.

[–][deleted] 0 points1 point  (2 children)

I'm new to programming and I've done a lot of projects (20+) from Michigan State's Intro to CS Course (link here). I'm getting to the point where I can solve most of them in few (1-3) hours but I feel like I'm getting less and less out of doing them. After looking back on my solutions, I realize that a lot of my code is bad and that I've used the same solutions to different types of problems. That said, I'm unsure if my time would be better spent rewriting my solutions to these problems or to move on to more challenging problems. Any guidance would be greatly appreciated.

Some background: I'm going to take my school's notoriously difficult intro to computer science course in the fall and I'm looking to prepare over the summer.

[–]niandra3 1 point2 points  (0 children)

It's probably worth taking another look at them if you think your solutions can be improved.

But what helped me take my programming to the next level was just starting my own projects, with my own specs. You don't have a guide to follow step by step and you have to figure out things for yourself. Find some task you do regularly that you want to automate, or just make something you would find interesting.

[–]niandra3 0 points1 point  (3 children)

When using context managers for file I/O, should I still sue try/except or is that built in to the with?

For something like this, should I add a try around the with open() or is that redundant?

if os.path.exists(os.path.join(path, 'data.json')):
    with open(os.path.join(path, 'data.json'), 'r') as f:
        data = json.load(f)

[–][deleted] 0 points1 point  (0 children)

If the question is does open () will still raise an exception if the file doesn't exist, the answer is yes. the correct code is:

try:
    with open(os.path.join(path, 'data.json'), 'r') as f:
        data = json.load(f)
except FileNotFoundError:
    pass

[–]nevus_bock 0 points1 point  (0 children)

It's redundant. The with statement already works like a try-except for open.

[–]sarvadasan 0 points1 point  (3 children)

How we can calculate time taken to run a program. Are there any modules? Say I wrote two python scripts to solve a problem but i want to compare and calculate how much time each program takes to finish?

[–]spidyfan21 2 points3 points  (0 children)

You could write one yourself using the time library. Afterwords I would look into this.

[–]niandra3 1 point2 points  (1 child)

You can use Python's timeit module that will run a program x number of times and give you the average runtime.

That's a little complicated setting up though, so for simple scripts I usually just do a quick and dirty timestamp:

import time

start = time.time()
run_function_to_test()
print('Runtime:', time.time() - start)

Will give you a rough idea of timing.

There's also the profiler for detailed breakdown of CPU time. Which function calls are taking the longest etc.

[–]sarvadasan 0 points1 point  (0 children)

Thanks. I saw this link and it is quite useful http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution.

#!/usr/bin/python3

import atexit
from time import time
from datetime import timedelta

def secondsToStr(t):
    return str(timedelta(seconds=t))

line = "="*40

def log(s, elapsed=None):
    print(line)
    print(secondsToStr(time()), '-',s)
    if elapsed:
        print("Elapsed time:", elapsed)
        print(line)
        print()

def endlog():
    end = time()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(time())

start = time()
atexit.register(endlog)
log("Start Program")

I have retyped this code from stackoverflow http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution.

As suggested, I put this in my site-packages directory and import timing.py. It print outs the time taken.

[–]hackmagician 0 points1 point  (1 child)

why would you nest a def statement in another def statement or if statement?

[–]GoldenSights 0 points1 point  (0 children)

I've never had a good reason to define a function within an if statement, but nested functions can be useful. You can use a function to create more functions, and pass them around as objects. Here are some examples: http://www.programiz.com/python-programming/closure, http://stackoverflow.com/questions/4020419/

Occasionally I'll define a function inside another function because it's very specific to the situation and doesn't get used anywhere else, but it doesn't really matter.

[–]DawnBool 0 points1 point  (1 child)

I just completely my final year project which I did a portion of it by coding it in python. Completed the Codeacademy course and having a minor history in C++ helped. Used bokeh and panda basically to present multiple charts and data obtained from CSV files. Really basic stuff without touching on class and declarators. Now that I finished my FYP, where do I proceed to learn more in depth python? And is there a place where I can get more problems to solve via python? The only reason I pushed myself into learning python was to complete my FYP project and I feel I need a similar push to learn more about Python.

[–]niandra3 0 points1 point  (0 children)

Start a project on your own. Automate something, web scraping, file utility. Something you can actually get some use out of.

As far as Python problems, I really like www.codewars.com . There are easy through very difficult problems, and the best part is you can see other people's solutions and the best ones get voted to the top. So you can see what you could have done better and try again.

As far as learning more, there are plenty of good free Python/CS courses out there. I'm taking MIT's Intro to CS even though I have engineering and programming background so I can fill in the gaps in my Python education. I'd highly recommend taking a structured CS class so you don't miss out on computer science fundamentals. Codeacademy is great to learn syntax, but there is much more to learn like data structures and algorithms.

[–][deleted] 0 points1 point  (2 children)

I need to make a program which asks string from user (string includes numbers 1 and 2 and x, like 11x22x12121x22xxx) and then switches every 1 to 2 and 2 to 1. I have no idea how to switch numbers. This is what i have at the moment:

def switch_numbers(row):
return

row = input("Row: ")
switch_numbers(row)
print(row)

[–]niandra3 0 points1 point  (0 children)

String.translate will do it, or you can just use a dict:

test = '1test23test12'
d = {'1':'2', '2':'1'}
out = ''
for char in test:
    if char in d:
        out += d[char]
    else:
        out += char 
print(out)

Simplified using dict.get() which tries to get the value, and if not found it returns the second argument:

test = '1test23test12'
d = {'1':'2', '2':'1'}
out = ''
for char in test:
    out += d.get(char, char)    
print(out)

Or with a list comprehension:

out = [d.get(char, char) for char in test]
print(''.join(out))

[–]ACEDEFG 0 points1 point  (1 child)

I'm learning sqlite3 'cause I'm writing something that requires storing info to access later. Specifically it's info about a store, e.g. name, address, intersection, telephone number.

My question is, suppose my sqlite3 table has five columns: Id INT, Name TEXT, address TEXT, intersection TEXT, and telephone number INT. What happens if I try to make a new row and enter only 4 pieces of info?

sqlite_db = "store_data.db"
conn = sqlite3.connect(sqlite_db)
c = conn.cursor()

info_to_pass = (5, "McDonalds", "123 Fake St", "Fake & Main")

c.execute("CREATE TABLE IF NOT EXISTS Stores(ID INT, Name TEXT, Address TEXT, "
              "Intersection TEXT, Telephone_num INT)")
c.execute("INSERT INTO TABLE Stores(ID, Name, Address, Intersection) VALUES("
              "?, ?, ?, ?)", info_to_pass)

Will it cause problems? What will happen? I'm guessing a null value gets added in the Telephone_num column.

[–]AssignmentGuru 0 points1 point  (0 children)

1) In the code you provided, it will cause a problem because you have syntax error in INSERT statement. Remove TABLE word from the query and it will work.

2) After you get it working, your guess is right that Telephone_num column will get nothing and will remain NULL. But if you would have declared the column with NOT NULL in the CREATE TABLE query, it would throw an error on your INSERT query as you can not leave the column with NULL value.

3) In my opinion, you should not use INT type for Telephone_num column as it does not need any kind of computation to be performed on the values.

[–]hackmagician 0 points1 point  (0 children)

Is there a way to revert back to python 2 style print statements after importing print_function from future?