Page 1 of 4 123 ... Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2003
    Location
    Canada
    Posts
    543
    Rep Power
    24

    Lightbulb Tips, tricks, inspiration, etc


    I had an idea to make a thread where people can post tips, tricks, thing to inspire or motivate people, links, etc.

    Hopefully this thread will be able to help any Pythoner. Whether it be a complete beginner or a very advanced expert.

    Tips: An example would be stuff that will help improve someone's programming. Such as: "Instead of using all of these functions, you can easily accomplish the same thing just using these two functions."

    Tricks: An example would be stuff that will help someone program faster.

    Inspiration: An example would be anything that serves as a great source of inspiration.

    Motivation: An example would be anything that helps motivate someone.

    Links: This could be newsgroups, mailing lists, IRC channels, web sites, etc.

    If people like this thread and post a lot of stuff, I will make a documentation.

    Enjoy!

    Comments on this post

    • mxatzis12 agrees : awesome!!!
    • codealot agrees
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    I like this idea. Hope ppl can try keep the msgs consice

    Here's a couple of things I just picked up.
    I'm on a few python mailing lists and this one came up recently.
    This is supposed to be much faster than providing a comparison function to list.sort()
    Code:
    unsorted_list = [{'id':99, 'title':'a'},{'id':42, 'title':'b'}, ... ] 
    decorated_list = [(x['id'],x) for x in unsorted_list]
    decorated_list.sort()
    sorted_list = [y for (x,y) in decorated_list]
    Another thing: using : 'dictarray = [{}]*10' creates only one dictionary, with ten references to it.
    whereas 'dictarray = [{} for i in range(10)]' creates 10 seperate dictionaries

    Cheers,
    Eli
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Sounds like a greate idea Chief! I've made this thead sticky for now and depending on how it goes i'll leave it that way .

    Link: http://www.python.org/doc/essays/styleguide.html

    The link points at the Python Style Guide, one of the main problems i find is everyone has a different style and some totaly different!

    Get Posting guys! Can't wait to see what other ppl add!

    Mark.
    Last edited by netytan; December 31st, 2003 at 04:43 PM.
    programming language development: www.netytan.com Hula

  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    TIP:
    Write unit tests! Python comes with PyUnit (the unittest module), and you should take advantage of that. It makes adding incremental improvements a LOT less painful because you can test and make sure your existing functionality isn't broken. In fact, the way we prefer to do tests on the IRC bot I'm working (link) is that you write the test first and then you code the functionality so that it passes the tests that you code. Same goes for bugs that we find. Instead of trying to fix the bug right away we write a test that (currently) pokes the bug and causes the error. Then we know the bug is fixed once we run the test and it passes.
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Oh yeah, just remembered another trick.

    If you're going to be building a string iteratively (in a loop, for example), then instead of using string concatenation each time, the most efficient way of doing it is actually aggregating the component strings into a list and then joining them. So, for example:

    Code:
    somedict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    L = []
    for (k,v) in somedict:
        L.append('%s (%s)' % (v, k))
    
    results = ' '.join(L)
    instead of:
    Code:
    somedict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    s = ""
    for (k,v) in somedict:
        s += '%s (%s) ' % (v, k)
    results = s[:-1]   # Remove trailing space
    Actually, I hadn't thought of the trailing space issue, but using a list makes that issue go away too

    The reason it's faster is because every time you concatenate a string it has to use 3 strings: the original, the stuff to add, and the result string (because strings are immutable!!, so you can't just add to the original string object). So all the build-up/tear-down time for each of those objects is incurred with each iteration. When using a list you just have to build a string and append it to a list (which is a cheap operation, no new objects required since lists are mutable) each time. Then you just join them at the end, which is cheaper than concatenating one at a time.
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  10. #6
  11. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69

    print without the new line...


    Usually not a problem but from time to time that extra \n can get in the way! Now before today i would have used sys.stdout.write(str) but i just discovered this handy little syntax treat.

    By adding an extra comma at the end of you're print statment you can actually avoid outputting the \n char i.e.

    Code:
    >>> for each in ('just', 'a', 'few', 'strings'):
    ...     print each
    ...     
    just
    a
    few
    strings
    >>> for each in ('just', 'a', 'few', 'strings'):
    ...     print each,
    ...     
    just a few strings
    >>>
    Mark.
    programming language development: www.netytan.com Hula

  12. #7
  13. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69

    PyCrust


    Just started using PyCrust, i'm very impressed so far, definatly a good enough reason to install wxPython even if you don't plan on doing any GUI development!

    Mark.
    programming language development: www.netytan.com Hula

  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2003
    Location
    Canada
    Posts
    543
    Rep Power
    24
    I just installed wxPython 2.4 for Python 2.3

    It's really cool! I also recommend you getting this wonderful thing.

    Not sure what PyCrust is? I'm quoting this from http://sourceforge.net/projects/pycrust/:

    PyCrust is an interactive Python shell written in Python using wxPython. PyCrust is now part of wxPython (www.wxpython.org), so packaged files are no longer available here, and the latest development version has moved to the wxWindows CVS repository.

    All of the replies so far work very well! Thanks guys! Keep them coming.
  16. #9
  17. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    PyCrust is awesum, yet another reason in my lets do away with Tkinter argument .

    When installing wxPython (on windows) a new folder is created in the menu; containing docs, examples and a few wx applications with a Pie icon... and one called PyCrust!

    Check it out!

    Mark.
    programming language development: www.netytan.com Hula

  18. #10
  19. onCsdfeu
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Canada
    Posts
    100
    Rep Power
    11
    Why the HECK did I never even tried these Py script ?

    Tell me, PyALaMode seems like a nice enough editor but... is there any to actually execute the files inside the shell ? Just like hitting F5 in IDLE.
  20. #11
  21. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    As far as i know it doesn't, but you can select all and copy you're program then 'paste plus' it into you're Python shell with the same effect as running (in theory).

    I would quite like to know why PyCrust, PyAlaMode etc arn't just one program... this would make an awesum IDE for Python! But it seems to be in pieces

    In any case the wxPython shell is definatly gonna replace IDLE for me!

    Mark.
    programming language development: www.netytan.com Hula

  22. #12
  23. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69

    Backticks


    I did something today i'd been wanting to do for a while... that is figure out what in hell backticks do in Python. And to my surprise what they actually did was no-where near what i expected having used perl.

    In perl backticks indicate system calls but in Python, using backticks is like putting an object directly into a string and escaping special chars that could cause a problem (kinda like raw strings) i.e.

    Code:
    >>> v1 = 'string'
    >>> v2 = "string"
    >>> v3 = 'C:\Documents and Settings\Mark\Desktop'
    >>> v4 = 'just a "string" in double quotes'
    >>> `v1`
    "'string'"
    >>> `v2`
    "'string'"
    >>> `v3`
    "'C:\\\\Documents and Settings\\\\Mark\\\\Desktop'"
    >>> `v4`
    '\'just a "string" in double quotes\''
    print `v1`
    'string'
    print `v2`
    'string'
    print `v3`
    'C:\\Documents and Settings\\Mark\\Desktop'
    print `v4`
    'just a "string" in double quotes'
    >>> v5 = (`v1`,`v2`,`v3`,`v4`)
    >>> v5
    ("'string'", "'string'", "'C:\\\\Documents and Settings\\\\Mark\\\\Desktop'", '\'just a "string" in double quotes\'')
    >>>
    Mark.
    programming language development: www.netytan.com Hula

  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Backticks are shorthand for repr(), basically.
  26. #14
  27. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Sweet , never actually had a use for repr() yet but is still nice to know. Thanks for the info!

    Mark.
    programming language development: www.netytan.com Hula

  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373

    Get to know the Python help system


    One of favourite features of Python is the extensive help system, but it is not well documented and many people probably don't know of it's existence. Spending a little time to learn how to use it can pay huge dividends.

    There are three components to the help system:

    1) the extensive documentation that is installed with Python. This is also available in a wide range of formats, including PDF, HTML and Windows Help. If you have installed the Windows version of Python then you will get the WinHelp version, but I recommend installing the HTML version as well, for reasons we shall see in a minute. Download it from http://www.python.org/doc/current/download.html and unzip it, then set the environment variable PYTHONDOCS to point to the directory.

    2) the interactive help system. Type help() at the interactive prompt and you will enter the help mode. You can get help on any module, class or function that has a docstring - not just from the modules that originally came with Python, but from any module on the path. If you have the HTML help files installed as described above, then you can also get help on a wide range of language features, such as keywords.
    When at the interactive prompt you can also get help directly for any object currently in the namespace, e.g.

    Code:
    >>> import string
    >>> help(string.atoi)
    Help on function atoi in module string:
    
    atoi(s, base=10)
        atoi(s [,base]) -> int
        
        Return the integer represented by the string s in the given
        base, which defaults to 10.  The string s must consist of one
        or more digits, possibly preceded by a sign.  If base is 0, it
        is chosen from the leading characters of s, 0 for octal, 0x or
        0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
        accepted.
    You can also get help on language features or from modules that are not currently imported by putting the help string in quotes:
    Code:
    >>> help('re.match')
    Help on function match in re:
    
    re.match = match(pattern, string, flags=0)
        Try to apply the pattern at the start of the string, returning
        a match object, or None if no match was found.
    Type help('modules') for a list of modules that Python currently knows about.

    3) there is a script that will run an HTTP server that will let you browse web pages generated dynamically from the __doc__ strings: PYTHON/tools/scripts/pydocgui.pyw. If you have installed the Windows version then you should have a shortcut to it set up in the Start menu called 'module docs'. Again, this Tkinter program displays help for any module on the path, not just the standard library. It also lets you search the __doc__ strings.

    Finally there is an excellent quick reference guide to Python available from http://rgruet.free.fr/#QuickRef.

    I believe that the combination of of the help system with the interactive mode and the simple, regular syntax make Python the easiest language on earth to learn.

    Dave - The Developers' Coach
Page 1 of 4 123 ... Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo