Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Cryolite
Oct 2, 2006
sodium aluminum fluoride
You can also use os.path.join to join paths instead of having to deal with escaped slashes.

Adbot
ADBOT LOVES YOU

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Thanks for the thoughts on coroutines, Dren. I did it that way and just put a brief explanation in the docstring. Added to that there is the fact that a ready made example is present as well due to the fact that I was writing it for a purpose (had a specific application for walking the filesystem).

Question: Should a module export its custom exceptions? I found out that the help() function respects __all__. But it seems to add unnecessary clutter to have the help list the custom exception class and a long list of double-underscore methods it inherits. Blah, blah, blah. It is a class of exceptions. Who would want to read that? So I thought perhaps __all__ should exclude the exceptions.

Dren
Jan 5, 2001

Pillbug

Plorkyeran posted:

Moving everything but the body of the try blocks to a decorator would make the coroutine-based code look pretty similar to regular functions.

For most coroutines you could get by with two decorators, @coroutine and @coroutine_sink where the latter does not do target.close() after handling a GeneratorExit.

Coroutines have a feature that precludes putting everything except the inside of the try block into the decorator, that you can do stuff before you start up the main while loop. E.g. consider a coroutine to do a grep.

Python code:
@coroutine
def grep(pattern, target):
    """Coroutine.  Forwards a line of text to its target if pattern is matched.
    
    arguments:
    pattern - regex pattern to match
    target  - coroutine to forward matching results to.
    """
    regex = re.compile(pattern)
    while True:
        try:
            line = (yield)
            match = regex.search(line)
            if match is not None:
                target.send(line)
        except GeneratorExit:
            target.close()
            return
An important aspect of this coroutine is that it compiles the regex pattern before it enters the main loop. (I know you could compile that regex before you pass it as an argument but this is just an example). Changing the decorator to move everything inside the try block would get rid of this flexibility.

Another issue is that a decorator that does everything but the contents of the try block would create an additional layer of function calls. This is what the current decorator looks like:
Python code:
def coroutine(func):
    """Initializes func as a coroutine.

    arguments:
    func - coroutine function to decorate
    """
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start
The first time it is called it initializes the coroutine then returns the coroutine function, which is then called directly by the code.

The type of decorator you're proposing would have to stick around permanently as another layer of function call.

Bunny Cuddlin
Dec 12, 2004

accipter posted:

A nice shortcut to starting this to browse to the directory with Windows Explorer, and then type "cmd" in the location bar and hit enter. That way you don't have to navigate to the required directory.

holy poo poo

bonds0097
Oct 23, 2010

I would cry but I don't think I can spare the moisture.
Pillbug

Bunny Cuddlin posted:

holy poo poo

You can also shift+right-click a folder and select 'Open Command Window Here'.

BannedNewbie
Apr 22, 2003

HOW ARE YOU? -> YOSHI?
FINE, THANK YOU. -> YOSHI.

bonds0097 posted:

You can also shift+right-click a folder and select 'Open Command Window Here'.

You can also do this by right clicking inside a folder if you have nothing selected.

ArcticZombie
Sep 15, 2010
Does lxml's ElementTree have anything similar to BeatifulSoup's find_previous_sibling()? I've been looking at its docs and playing around with it, I can't see anything I can use for this but I'm a newbie so I could be missing something. I'm using lxml to parse the xml for BeatifulSoup anyway so I thought I could perhaps cut out a dependency.

Aafter
Apr 14, 2009

A is for After.
Newbie here! Doing Udacity's CS101 class and I'm getting a syntax error.

code:
def stamps(cash):
    fiveP = cash / 5
    twoP = (cash - (fiveP * fiveP) / 2
    oneP = cash - (fiveP * fiveP) - (twoP * twoP)

    return fiveP, twoP, oneP
The syntax error is on oneP.

Houston Rockets
Apr 15, 2006

You're missing a closing parenthesis at the end of the twoP assignment.

Aafter
Apr 14, 2009

A is for After.
I feel dumb. :D

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I have a Python module, let us call it x.py, I wrote for myself that I now want to be in version control. So I made a directory called simply x, moved x.py in there, and initialised a git repository. So far so simple. But now in order to import that module I have to type

import x.x as x

Which is kind of onerous. I could add the directory x to my PYTHONPATH, but I don't want to do that for every module I create. I could put a copy of x in my Python install directory, but I'd have to update it each time I make a change. But I see that I can rename x.py to __init__.py and I can once again just "import x". So now I have a directory containing a single file, "__init__.py" (and a .gitignore file and git/pycache nonsense). Is there a better way?

QuarkJets
Sep 8, 2008

Hammerite posted:

I have a Python module, let us call it x.py, I wrote for myself that I now want to be in version control. So I made a directory called simply x, moved x.py in there, and initialised a git repository. So far so simple. But now in order to import that module I have to type

import x.x as x

Which is kind of onerous. I could add the directory x to my PYTHONPATH, but I don't want to do that for every module I create. I could put a copy of x in my Python install directory, but I'd have to update it each time I make a change. But I see that I can rename x.py to __init__.py and I can once again just "import x". So now I have a directory containing a single file, "__init__.py" (and a .gitignore file and git/pycache nonsense). Is there a better way?

You could do "from x import x"

Or you could just create a single python directory, turn it into a git repository, point your PYTHONPATH at it, and then drop x.py and any other python modules into it. If there are some modules that you don't want to version control, then just don't add them to the repository

Nippashish
Nov 2, 2005

Let me see you dance!
You can put from x import * into __init__.py. This will let you import x and then access its members like x.fancy_things().

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Thanks, I decided to bite the bullet and split the thing up into a half dozen files. After a bit of faffing around with import statements and so on the organisation of the code is now improved.

Dominoes
Sep 20, 2007

Issue/question with PyQT / resources / cx_freeze.

I'm using QT's resource system to set an application icon. (Goes in the top left corner of the Window for Windows programs) I created the resource in Designer, then used pyrcc4 to create a rc.py file. It works properly on my uncompiled program, but fails to show (Shows the generic windows program icon instead) when compiling the script with cx_freeze. Note that I am not referring to the icon you click to launch the program - that's not handled by QT, and works properly. Any ideas? This is my setup.py.

Python code:
from sys import platform
from cx_Freeze import setup, Executable

import module_locator

_dir = module_locator.module_path()

base = None
if platform == "win32":
    base = "Win32GUI"

setup(
    name = "Plates",
    version = "0.1",
    description = "Downloads approach plates",
    executables = [Executable(_dir + '\\plates.pyw',
    base = base, icon = _dir + '\\icon.ico')],
    )
I get no errors when building the program. My rc file does exist (as a compiled python file) in library.zip.

edit: Solved, from Stack Overflow. The solution is to copy the imageformats folder from the PyQT directory to my program's directory. The image folder was (Windows) in Python33\Lib\site-packages\PyQt4\plugins.

Dominoes fucked around with this message at 01:47 on May 31, 2013

huge pile of hamburger
Nov 4, 2009
I have an python XML parsing problem that I can't seem to figure out.

I have the following XML:
code:
<data>
  <data_in base="base64">
  </data_in>
  <log_sense_data>
    <ds base="bool">1</ds>
    <spf base="bool">0</spf>
    <page_code base="hex">15</page_code>
    <background_scan_results_log_page>
      <parameter>
        <parameter_code base="hex">0000</parameter_code>
        <du base="bool">0</du>
        <tsd base="bool">0</tsd>
        <etc base="bool">0</etc>
        <tmc base="hex">00</tmc>
        <format_linking base="hex">03</format_linking>
        <parameter_length base="dec">12</parameter_length>
        <description base="string">background scanning status parameter</description>
        <accumulated_power_on_minutes base="dec">579578</accumulated_power_on_minutes>
        <background_scanning_status base="hex">01</background_scanning_status>
        <number_of_background_scans_performed base="dec">112</number_of_background_scans_performed>
        <background_scan_progress base="hex">00000036</background_scan_progress>
        <number_of_background_medium_scans_performed base="dec">112</number_of_background_medium_scans_performed>
      </parameter>
      <parameter>
        <parameter_code base="hex">0001</parameter_code>
        <du base="bool">0</du>
        <tsd base="bool">0</tsd>
        <etc base="bool">0</etc>
        <tmc base="hex">00</tmc>
        <format_linking base="hex">03</format_linking>
        <parameter_length base="dec">20</parameter_length>
        <description base="string">background medium scan parameter</description>
        <accumulated_power_on_minutes base="dec">82932</accumulated_power_on_minutes>
        <reassign_status base="hex">05</reassign_status>
        <sense_key base="hex">01</sense_key>
        <additional_sense_code base="hex">17</additional_sense_code>
        <additional_sense_code_qualifier base="hex">01</additional_sense_code_qualifier>
        <vendor_specific base="hex">20e2570187</vendor_specific>
        <logical_block_address base="hex">00000000478994d8</logical_block_address>
      </parameter>
      <parameter>
        <parameter_code base="hex">0002</parameter_code>
        <du base="bool">0</du>
        <tsd base="bool">0</tsd>
        <etc base="bool">0</etc>
        <tmc base="hex">00</tmc>
        <format_linking base="hex">03</format_linking>
        <parameter_length base="dec">20</parameter_length>
        <description base="string">background medium scan parameter</description>
        <accumulated_power_on_minutes base="dec">104467</accumulated_power_on_minutes>
        <reassign_status base="hex">05</reassign_status>
        <sense_key base="hex">01</sense_key>
        <additional_sense_code base="hex">18</additional_sense_code>
        <additional_sense_code_qualifier base="hex">07</additional_sense_code_qualifier>
        <vendor_specific base="hex">203ab846ea</vendor_specific>
        <logical_block_address base="hex">00000000133d5046</logical_block_address>
      </parameter>
    </background_scan_results_log_page>
  </log_sense_data>
</data>
Where Parameter_code 0000 will always exist, and there could be any number of parameter_codes after that. Esentially I want to pull 2 values (power on minutes, background scans) from parameter_code 0000, as well as most values from parameter_code 0001 and greater, to be later put into a database. The code I have so far is this:

code:
import xml.etree.ElementTree as et
log_page_tree = et.fromstring(results['Data']['RawData'])
if log_page_tree.find('log_sense_data') == None:
        continue
    else:
        for element in log_page_tree.find('log_sense_data'):
            for pagecode in element.iter('page_code'):
                if pagecode.text == '15':
                    for param in log_page_tree.find('log_sense_data').find('background_scan_results_log_page'):
                        for derp in param.iter():
                            print derp.tag, derp.text
			    #for totalpoweron in param.iter('accumulated_power_on_minutes'):
                                    #print totalpoweron.text
I want to be able to keep the 2 values from parameter_code 0000, while iterating through the rest of the parameter_codes to be put into a database. Can anyone give me a push in the right direction here? If I specify param.iter('somevalue') to grab each value, the code doesn't seem to iterate.

The Gripper
Sep 14, 2004
i am winner

watwat posted:

I have an python XML parsing problem that I can't seem to figure out.

I have the following XML:

I want to be able to keep the 2 values from parameter_code 0000, while iterating through the rest of the parameter_codes to be put into a database. Can anyone give me a push in the right direction here? If I specify param.iter('somevalue') to grab each value, the code doesn't seem to iterate.
You might be overthinking it, I'd personally do something like this, assuming your XML is accurate:
Python code:
n = log_page_tree.findall("./log_sense_data/background_scan_results_log_page/parameter")
# check if result is not None or empty array here!

for x in n:
    parameter_code =  x.find("./parameter_code").text
    print "## parameter_code: %s ##" % parameter_code

    if parameter_code == "0000":
	# should probably check if x.find(<whatever>) is not None before using
        print "\taccumulated_power_on_minutes: %s" % x.find('./accumulated_power_on_minutes').text
        print "\tnumber_of_background_medium_scans_performed: %s" % x.find('./number_of_background_medium_scans_performed').text

    else:
        fields = x.findall('./')
        for field in fields:
            print "\t%s: %s" % (field.tag, field.text)
Which basically just selects all the parameter tags, displays just the two fixed fields for parameter_code 0000 and dumps all the fields for the others by just selecting them directly.

The Gripper fucked around with this message at 11:45 on May 30, 2013

Dominoes
Sep 20, 2007

edit: nvm

Dominoes fucked around with this message at 02:49 on Jun 1, 2013

duck monster
Dec 15, 2004

Sab669 posted:

So a buddy of mine is going back to college to get a BS in Comp Sci in a few months, and I have a really dumb question. He decided to start with the MIT lecture last night and I guess it starts off having him use Python. I don't know the first thing about Python or the Python Shell application it was having him use (Or any scripting language for that matter, I'm a newbie C# guy). He was having a problem trying to "understand" how he would actually use this in the real world. By that I mean, if he saved a file and ran it, a command window would pop up and immediately disappear, even though the script requests user input.

I also think part of it for him is he expects to be creating full blown desktop applications, but you need to learn to walk before you can run. Most day-to-day users would poop themselves if they had to deal with the command line in any way.

He was just texting me about it this morning as I was getting ready for work, so I didn't have a chance to sit down and try to learn anything, though I figured while he's taking this course I probably should too :)

http://kivy.org/

Its got a few rough edges in terms of the fact its a young project and evolving fast, but its very actively maintained and actually achieves cross platform (including ios(!) and android) really well.

And the apps look pretty nice if you like black things.

bigmandan
Sep 11, 2001

lol internet
College Slice
That kivy framework looks pretty neat. I've been looking for something like this for a small side project I'm working on and it might just fit what I need.

Nybble
Jun 28, 2008

praise chuck, raise heck
Just a end-of-day frustration I just found in our code:

code:
sql = '''
   SELECT %s FROM table_number_%s 
   WHERE agency_id = %%s
''' % column, number

result = self._query(sql, (agency_id))
Resulting SQL:
code:
 SELECT vehicle FROM table_number_4 WHERE agency_id=16 
Yes. That's two string substitutions in a row, with no other instructions inbetween. The Double Percentage (%%) which is commonly used to do a literal '%' is in place so it can be substituted later.

:smithicide:

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

What library would be recommended for doing some 3D geometry stuff? I need to calculate dihedral angles and best fit planes for a list of points, checking coplanarity and combining coplanar triangles into polygon faces.

Dominoes
Sep 20, 2007

I'm getting ready to release my first program. Since I'm new to programming and don't know what the hell I'm doing, I'm looking for feedback on the overall layout of my code. It seems functional, but may appear hideously disfigured on the inside to an experienced coder. Let me know what you think, and if you have any suggestions.

Main Python file (should open directly in browser)

Standalone Windows binary

Dominoes fucked around with this message at 00:27 on Jun 4, 2013

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

I'm getting ready to release my first program. Since I'm new to programming and don't know what the hell I'm doing, I'm looking for feedback on the overall layout of my code. It seems functional, but may appear hideously disfigured on the inside to an experienced coder. Let me know what you think, and if you have any suggestions.

Main Python file (should open directly in browser)

Standalone Windows binary

Some general thoughts here, but none if it's that big of a deal:

I try to avoid doing "from X import Y". Throughout your code where you use Y, it's better if you know that it came from X. Explicit is better than impicit.
code:
def add(self):
#Adds a plate input by the user
    ident = self.ui.le_ident.text()
is usually...
code:
def add(self):
    #Adds a plate input by the user
    ident = self.ui.le_ident.text()
or even better...
code:
def add(self):
    """
    Adds a plate input by the user
    """
    ident = self.ui.le_ident.text()
Instead of this:
code:
save(_plates, dir + 'save.yaml')
do this:
code:
save(_plates, os.path.join(dir,' save.yaml'))
In fact, I don't like that you have a save() function and a save() method. I'd probably just have the save() method, but maybe you have a good reason for having the save functionality in its own function. Even if you do, I don't like them having the same name.

Dominoes
Sep 20, 2007

Thermopyle posted:

Some general thoughts here, but none if it's that big of a deal:

I try to avoid doing "from X import Y". Throughout your code where you use Y, it's better if you know that it came from X. Explicit is better than impicit.
code:
def add(self):
#Adds a plate input by the user
    ident = self.ui.le_ident.text()
is usually...
code:
def add(self):
    #Adds a plate input by the user
    ident = self.ui.le_ident.text()
or even better...
code:
def add(self):
    """
    Adds a plate input by the user
    """
    ident = self.ui.le_ident.text()
Instead of this:
code:
save(_plates, dir + 'save.yaml')
do this:
code:
save(_plates, os.path.join(dir,' save.yaml'))
In fact, I don't like that you have a save() function and a save() method. I'd probably just have the save() method, but maybe you have a good reason for having the save functionality in its own function. Even if you do, I don't like them having the same name.

Thank you. I've indented the function descriptor comments. I thought I read somewhere that docstring notation should only be used for long strings, not comments. Is this valid, or did I misinterpret something?

I've been using 'from x import y' to make the code easier to read. I have an easier time comprehending shorter lines, especially in cases like this where the additional code is always the same. I've been looking at it similar to functions' importance: It allows me to reuse code instead of typing the same thing multiple times. Is my reasoning valid/common, or should I use 'import x' for everything? I also have a counter-reason for the downside of not knowing where an expression in the program body came from: Not knowing what a module from the import list is used for. Along the same reasoning with shorter code, what's the reason for using os.path.join() instead of + ?

I've changed the names of the save() Main class methods to save_gui. I don't have a good grasp on the layout of QT code, and agree that having separate methods and functions for save() is messy. It's set up that way, because things involving input from the GUI seem to only work if they're in the Main() QT class. So, I send the input to these class methods, then have them call my main program's functions, which do most of the work. I like to keep as much of my code as possible in my own functions and classes.

Dominoes fucked around with this message at 03:04 on Jun 4, 2013

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Dominoes posted:

Thank you. I've indented the function descriptor comments. I thought I read somewhere that docstring notation should only be used for long strings, not comments. Is this valid, or did I misinterpret something?
The term "docstring" specifically refers to a string literal that is the first statement in a module, function, class or method definition. These strings serve as documentation for the user of the function/class/module and are accessible programmatically through __doc__ attributes. IPython lets you easily view these:

code:
In [1]: def f():
   ...:     """
   ...:     Returns 3.
   ...:     """
   ...:     return 3
   ...: 

In [2]: f.__doc__
Out[2]: '\n    Returns 3.\n    '

In [3]: f?
Type:       function
String Form:<function f at 0x7ff9f8d75170>
File:       /home/me/<ipython-input-1-0bdede9e8aca>
Definition: f()
Docstring:  Returns 3.
Triple-quoted strings, in general, are not called "docstrings". Using triple quotes simply lets you write a string literal across multiple lines without having to use \n escape sequences. You are right that you shouldn't use triple-quoted strings as comments in the middle of a function/class/module.

Dominoes posted:

I've been using 'from x import y' to make the code easier to read. I have an easier time comprehending shorter lines, especially in cases like this where the additional code is always the same. I've been looking at it similar to functions' importance: It allows me to reuse code instead of typing the same thing multiple times. Is my reasoning valid/common, or should I use 'import x' for everything? I also have a counter-reason for the downside of not knowing where an expression in the program body came from: Not knowing what a module from the import list is used for.

I almost always use from module import whatever -- this is personal style. If I want to see where some name is defined, I control-click it in PyCharm or use grep.

Dominoes posted:

Along the same reasoning with shorter code, what's the reason for using os.path.join() instead of + ?

I was unable to run your code on my (Linux) laptop since you've hard-coded Windows path separators. os.path.join uses / or \ as appropriate on different platforms and has a few other advantages over manually concatenating filesystem paths. I also do from os.path import join as ospj to use a shorter (but still descriptive and greppable) function name.

Dominoes
Sep 20, 2007

Lysidas posted:

The term "docstring" specifically refers to a string literal that is the first statement in a module, function, class or method definition. These strings serve as documentation for the user of the function/class/module and are accessible programmatically through __doc__ attributes. IPython lets you easily view these:

Triple-quoted strings, in general, are not called "docstrings". Using triple quotes simply lets you write a string literal across multiple lines without having to use \n escape sequences. You are right that you shouldn't use triple-quoted strings as comments in the middle of a function/class/module.
Thank you. I assumed triple-quoting and docstrings were synonymous. The only place I'd used one is in a different program that uses a markup language called FIXML. I used them to enclose the FIXML, to send in a POST request. I'll take a look at using it at the beginning of functions instead of #.

Lysidas posted:

I was unable to run your code on my (Linux) laptop since you've hard-coded Windows path separators. os.path.join uses / or \ as appropriate on different platforms and has a few other advantages over manually concatenating filesystem paths. I also do from os.path import join as ospj to use a shorter (but still descriptive and greppable) function name.
That's a drat good reason; changed. Stealing ospj too, so as not to conflict with the normal join().

Dominoes fucked around with this message at 03:06 on Jun 4, 2013

bonds0097
Oct 23, 2010

I would cry but I don't think I can spare the moisture.
Pillbug
I like 'from X import Y', it explicitly defines (at the top of your code) what imported names will be present in your code and I find that very helpful compared to just an 'import X' (what exactly is the author using from X? what's its purpose? I have to read/grep through to get a clue). As noted, this certainly seems appropriately subjective and can be chalked up to personal style.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Thank you. I've indented the function descriptor comments. I thought I read somewhere that docstring notation should only be used for long strings, not comments. Is this valid, or did I misinterpret something?

Note what PEP-257 says about one-line docstrings. I prefer the multi-line format for single-line docstrings despite what 257 says about it not looking as good, but it's not a big deal.


Dominoes posted:

I've been using 'from x import y' to make the code easier to read. I have an easier time comprehending shorter lines, especially in cases like this where the additional code is always the same. I've been looking at it similar to functions' importance: It allows me to reuse code instead of typing the same thing multiple times. Is my reasoning valid/common, or should I use 'import x' for everything?

Here's what Guido has to say on the matter when someone said that they preferred to do it your way:

quote:

You would be wrong (unless you got your examples swapped around :-).
For example, it's part of the Google Python style guides that all
imports must import a module, not a class or function from that
module. There are way more classes and functions than there are
modules, so recalling where a particular thing comes from is much
easier if it is prefixed with a module name. Often multiple modules
happen to define things with the same name -- so a reader of the code
doesn't have to go back to the top of the file to see from which
module a given name is imported.

It's not as big of an issue on a small file like yours, especially when it's all fresh in your mind. However, in 12 months, after the code has quadrupled in size, seeing a reference to load() in the middle of your code instead of yaml.load() is going to be confusing. Where did this load() come from? Wait, why is there a loads() in here as well? ITS SO CONFUSING!

Dominoes posted:

I also have a counter-reason for the downside of not knowing where an expression in the program body came from: Not knowing what a module from the import list is used for.

Even if you have a good reason for caring (I can't think of a reason off the top of my head), it's going to be much less frequent that you care about this rather than having to scroll to the top of the file for the bajillionth time to see where this load() function came from.

Dominoes posted:

Along the same reasoning with shorter code, what's the reason for using os.path.join() instead of + ?
Because os.path.join() will take care of edge cases. Because it makes what you're doing explicit. Again, in 12 months when you're looking at this code it's more obvious what os.path.join(dir, file) is doing AND what dir and file are.

Basically, this: http://stackoverflow.com/questions/13944387/why-use-os-path-join-over-string-concatenation

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Thermopyle posted:

It's not as big of an issue on a small file like yours, especially when it's all fresh in your mind. However, in 12 months, after the code has quadrupled in size, seeing a reference to load() in the middle of your code instead of yaml.load() is going to be confusing. Where did this load() come from? Wait, why is there a loads() in here as well? ITS SO CONFUSING!


Even if you have a good reason for caring (I can't think of a reason off the top of my head), it's going to be much less frequent that you care about this rather than having to scroll to the top of the file for the bajillionth time to see where this load() function came from.

For this reason, json is one module that I always import in its entirety. You're right that load() is too general when you're looking at the file a few months from now.

A lot of the standard library classes and functions are named descriptively enough, though. These are the stdlib imports from one of my relatively recent scripts:

Python code:
from argparse import ArgumentParser
from functools import partial
from multiprocessing import Pool
from os import remove
from os.path import (abspath, basename, expanduser, getsize, isfile,
    join as ospj, relpath, split as osps, splitext)
from tempfile import NamedTemporaryFile
Most of these are perfectly clear without having to use the full module name every time. ospj and osps aren't obvious from their (acronym) names, but are easy to remember once you see the definition. functools.partial, multiprocessing.Pool and os.remove are kind of questionable, but I think these names are still distinct enough. I've never felt the need to name a function partial or remove or name a class Pool.

Guido's absolutely right in that it's good to avoid ambiguity, but lots of the functions/classes in the standard library are clear enough on their own.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

You can also use os.sep instead of hardcoding separators.

Dominoes
Sep 20, 2007

Thermopyle posted:

It's not as big of an issue on a small file like yours, especially when it's all fresh in your mind. However, in 12 months, after the code has quadrupled in size, seeing a reference to load() in the middle of your code instead of yaml.load() is going to be confusing. Where did this load() come from? Wait, why is there a loads() in here as well? ITS SO CONFUSING!

Lysidas posted:

For this reason, json is one module that I always import in its entirety. You're right that load() is too general when you're looking at the file a few months from now.
So I went in and changed the json and yaml imports 'import json' and 'import yaml'. Json uses 'loads', yaml uses 'load'. Neither are very specific on their own, and especially not when using both. I'm using both since JSON seems more universal, but doesn't support objects, while YAML does. It turns out, I left off an 's' in the code that reads a JSON file some time ago... The YAML module was loading the JSON file the whole time, which I didn't know it could do. Reason for being careful about imported method names demonstrated!

Dominoes fucked around with this message at 04:23 on Jun 4, 2013

QuarkJets
Sep 8, 2008

I also prefer "from x import y" in most circumstances, only using "import x" if I use a lot of different features from that module. But there's a reason that you can do both: personal preference

Thermopyle, why is a """single-line docstring""" better than #single-line docstring? They serve the same purpose and do the same thing but # is a lot cleaner looking when you only have one line

Nybble posted:

Just a end-of-day frustration I just found in our code:

code:
sql = '''
   SELECT %s FROM table_number_%s 
   WHERE agency_id = %%s
''' % column, number

result = self._query(sql, (agency_id))
Resulting SQL:
code:
 SELECT vehicle FROM table_number_4 WHERE agency_id=16 
Yes. That's two string substitutions in a row, with no other instructions inbetween. The Double Percentage (%%) which is commonly used to do a literal '%' is in place so it can be substituted later.

:smithicide:

That's why I don't bother loving around with MySQLdb's bizarre variable substitution nonsense and just do it myself using Python

code:
sql = "select %s" % column + \
        " from %s" % number + \
        " where agency_id = %d" % agency_id
Seriously, is there any reason to use MySQLdb's variable substitution mechanisms instead of just building the strings yourself?

Opinion Haver
Apr 9, 2007

QuarkJets posted:

Seriously, is there any reason to use MySQLdb's variable substitution mechanisms instead of just building the strings yourself?

Not being vulnerable to SQL injection attacks?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

yaoi prophet posted:

Not being vulnerable to SQL injection attacks?

Yeah, let the database library deal with working out whether quotes should go around a thing, how a string should be escaped, etc. Don't write PHP in Python :wth:

As for importing names from a module, if you want it to be clear from the import statement what you are using something for _and_ you want the thing to have a descriptive name, you can always do

from someModule import someName as descriptiveName

(I'm sure someone will criticise me for this because omg someone who sees descriptiveName in use will have to go look for the line where it is imported, how could you do that!!! but I'll just say in advance that I think the upsides outweigh that, as long as the file is not enormous (which it shouldn't be))

QuarkJets
Sep 8, 2008

yaoi prophet posted:

Not being vulnerable to SQL injection attacks?

Seems like a good enough reason, but only for queries that use user inputs, right? Are there others?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

QuarkJets posted:

Seems like a good enough reason, but only for queries that use user input, right? Are there others?

If you use it for queries that use user input (and I agree you should), then IMO for consistency reasons alone you should do it everywhere.

n0manarmy
Mar 18, 2003

Going crazy with Python GUI crap. I've switched from TKinter to PyQt (using pyside) and cannot seem to figure out how to approach the below program concept. It could be that the concept is all wrong as well, so if it is, be gentle and provide some direction on how re-evaluate the concept.

I'm creating a class for the GUI components and am trying to create buttons to switch between one layout and another. I was able to do this in TKinter by obfuscating the create/destroy of the frames that contained the various functions of each menu.

main python file:
-Class
--Intro Menu
--Player Select Menu
--Difficulty Settings Menu
--Main Game Window
--etc...
-main
--Create class
-if name main
--main

Through out my googling, I've not really found any good tutorials on how to handle multiple windowed applications. I understand that Python might not be the best programming language for this but its the language I prefer right now. I've found references to QStackedlayout and setlayout, however I have not found anything to help with the concept of how to best build multiple windowed apps like above. Also reading the QT libraries are difficult for me because they tend to be in a C/C++ style for function use.


Reasoning:
I'm attempting to remake a very old game as a way to dig myself in to Python and GUI programming. The repetition of programming the game should help the language stick a bit, as well as allow me to further improve on the application as my programming progresses.

The game is Jones In The Fastlane and all I've done so far is load up the original and collect all the data points and GUI windows in to notes. I know what needs to go in and have an idea of what to expect. I was planning on building all of the menu components, creating all the variables in the process, and then putting it all together with the engine.

n0manarmy fucked around with this message at 14:57 on Jun 4, 2013

Dominoes
Sep 20, 2007

n0manarmy posted:

Going crazy with Python GUI crap. I've switched from TKinter to PyQt (using pyside) and cannot seem to figure out how to approach the below program concept. It could be that the concept is all wrong as well, so if it is, be gentle and provide some direction on how re-evaluate the concept.

I'm creating a class for the GUI components and am trying to create buttons to switch between one layout and another. I was able to do this in TKinter by obfuscating the create/destroy of the frames that contained the various functions of each menu.

main python file:
-Class
--Intro Menu
--Player Select Menu
--Difficulty Settings Menu
--Main Game Window
--etc...

-main
--Create class
-if name main
--main

Through out my googling, I've not really found any good tutorials on how to handle multiple windowed applications. I understand that Python might not be the best programming language for this but its the language I prefer right now. I've found references to QStackedlayout and setlayout, however I have not found anything to help with the concept of how to best build multiple windowed apps like above. Also reading the QT libraries are difficult for me because they tend to be in a C/C++ style for function use.


Reasoning:
I'm attempting to remake a very old game as a way to dig myself in to Python and GUI programming. The repetition of programming the game should help the language stick a bit, as well as allow me to further improve on the application as my programming progresses.

The game is Jones In The Fastlane and all I've done so far is load up the original and collect all the data points and GUI windows in to notes. I know what needs to go in and have an idea of what to expect. I was planning on building all of the menu components, creating all the variables in the process, and then putting it all together with the engine.
Throwing in a disclaimer of I don't know what I'm doing, but here's what I've been doing, which seems to work for standard GUI elements. No idea if the same layout works for custom graphics.

Main program file:
-QT class that is an instance of QtGui.QMainWindow. Looks like this:
code:
from plates_gui import Ui_Main
from about_gui import Ui_About

class Main(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Main()
        self.ui.setupUi(self)
        self.ui.btn.clicked.connect(self.signal)
	
    def method(self):
        x = self.ui.inputfield.text()
It contains some boilerplate stuff, and functions that take input directly from the QT window.
-Separate classes for each window. ie:
code:
class About(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_About()
        self.ui.setupUi(self)
-Main program body. Able to manipulate the GUI elements, but not accept user input from them.
-boilerplate stuff at the end. Also put global variables that affect the GUI, and anything that needs to happen with the GUI at startup here.
code:
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
I've been using QT designer, and have separate files, called by the QT class in the main program, for the GUI layout. You could write the code yourself if you wanted.

Example I posted last night. Has a link to the main program file, and the full, compiled Windows program with source code.

Dominoes fucked around with this message at 15:06 on Jun 4, 2013

Adbot
ADBOT LOVES YOU

BigRedDot
Mar 6, 2008

QuarkJets posted:

Thermopyle, why is a """single-line docstring""" better than #single-line docstring? They serve the same purpose and do the same thing but # is a lot cleaner looking when you only have one line
Because one is actually a doctstring, which plays nice with python's help system, introspection systems, and API documentation tools, and the other is not.

  • Locked thread