News:

Testimonial: "PD is the home of Pure Evil and All That Is Wrong With the Interwebz." - Queen of the Ryche, apparently in all seriousness

Main Menu

Python lessons

Started by Triple Zero, January 26, 2012, 09:02:04 PM

Previous topic - Next topic

Bu🤠ns

Quote from: Golden Applesauce on February 04, 2012, 01:34:15 AM
Last time I checked (which was a while ago), py2exe didn't support all of Python.

When you say "it doesn't work" do you mean that you got an .exe that didn't do what the .py did, or that it failed to produce an .exe at all?
If the latter, looking for the error message py2exe gave you on StackOverflow (or just the general internet) is a good place to start.

If you're going with portable python, you can also strip out any .py file that has a corresponding .pyc file.  (I think, haven't tried it personally.  If that doesn't work, you almost certainly do it the other way around and remove the .pyc's.)  You could also consider just installing python on your friends computers; if they're non-technical, they probably already have tons of random software lying around taking up space, and if they are somewhat technical, they need Python.

Another option:
See if your program works with http://www.skulpt.org/ .  If it does, you can just have your friends run python through their web browsers.

Ah thanks!

I found a binary py2exe that seemed to install the missing dlls (MSVCR90.dll) appropriately.  I tried it manually but I must have messed up along the way at some point...not sure, but it works now :D so that's enough for me at this point.  I also found Pyinstaller but i haven't tried it yet since py2exe seems to work.  But www.skulpt.org will definitely come in handy, thanks!

Triple Zero

Quote from: Triple Zero on January 26, 2012, 09:02:04 PMI believe there's several people on PD learning python (Faust, BDS), apparently Google's tutorials are pretty good:

http://blog.hartleybrody.com/2012/01/google-python/
http://sumukh.me/GFM5+ (PDF that's linked on the blog, in case it's down)


It was just brought to my attention that these Google tuts implicitly seem to imply that you're supposed to indent with two spaces in Python.

This is of course wrong, the Python Style Guide PEP 0008 is pretty clear that four spaces is the convention.

Now this one is pretty arbitrary, but most of the recommendations in PEP 0008 are just plain common sense, and recommended if you want to write pretty Python code. One of the recommendations, for instance, is consistency, which means that if you're adapting from someone else's code, and they use different style conventions, you should probably follow those, or it'll become a mess. And since most of the Python community follows PEP 0008, it therefore follows that it's probably best to get in the habit of using four spaces yourself, just in case your code might some day touch someone else's code.

Another really good recommendation is that A Foolish Consistency is the Hobgoblin of Little Minds, meaning that you should not be consistent when it's better that you don't. AKA Think For Yourself, Schmuck!

If you got any other questions about Python style, start your Python interpreter and type import this

If you don't have an interpreter handy, use this one: http://shell.appspot.com/  (it doesn't work on skulpt.org, it seems. also that appspot thing is overloaded and gives 500 errors often cause it's just a demo site)
Ex-Soviet Bloc Sexual Attack Swede of Tomorrow™
e-prime disclaimer: let it seem fairly unclear I understand the apparent subjectivity of the above statements. maybe.

INFORMATION SO POWERFUL, YOU ACTUALLY NEED LESS.

minuspace

#17
Quote from: Triple Zero on January 28, 2012, 12:53:10 AM

Are you into generative art, by any chance?

Yea, even if just sequencing I like the stuff to somehow feel alive, surprises and such.  I like building moving sound sculptures - and it also helps to sometimes have more complex automation when taking an orientation break during performance.  It's a guilty pleasure of mine.

Not to push my vices, still, nodebox.net is cool like processing (above)

Oh, and yea, I think it's python...

Rumckle

Thanks for this Trip, I have to start using this image processing program that is Python based, so this is really useful.

Quote from: Triple Zero on January 27, 2012, 01:09:53 AM
If you're on Linux, I personally like to use gEdit, since it's really lightweight, but can be made to do all sorts of amazing things if you install the right plugins. Hard-core Linux coders seem to generally prefer Vim or Emacs, though. Vim's got a very steep learning curve because it operates rather differently than any text-editor you're probably used to, but there's a load of tutorials out there, especially since for some reason last year it got a surge in popularity. Emacs is easier to use right away, but it's huuuuuuuuge. Both Emacs and Vim can literally do anything.


Is there any plugins you'd suggest for gedit? I've been using it for a couple of months now, but I haven't looked at plugins.
It's not trolling, it's just satire.

Triple Zero

Code comment -- Comment out or uncomment a selected block of code.
External Tools -- Execute external commands and shell scripts. You can do a *lot* of powerful stuff with this, if you're creative. For instance I added the following bit of script:
#!/usr/bin/python
print input()

With hotkey set to ctrl-shift-P, input to "current selection" and output to "replace selection", you can write *any* Python expression, select it, ctrl-shift-P and it gets evaluated and replaced. I mainly use it for small calculations such as 55+23+88+9 or whatever, but you can potentially go crazy with it.

Actually, turns out I don't even use that many coding specific ones.

Here's some general plugins that I've also enabled:

Document Statistics -- Analyzes the current document and reports the number of words, lines, characters and non-space characters in it.
Change Case -- Changes the case of the selected text.
Join/Split Lines -- exactly what it says on the label.

There's also a Python Console plugin, which gives you an interactive Python interpreter in a bottom pane. Very nice, but the default Python interactive interpreter is pretty basic. It works but it doesn't do completion, not much inspection--actually I just tried it and it's smoother than I expected, maybe it works for you.

There are also some third-party gedit plugins that do things like code completion and such, which is really nice, but I'm not sure why I am apparently not using those. Maybe they didn't work right, or got in the way. Or maybe I just figured I didn't need them because IPython's completion is superior anyway.

Indeed, if you're on Linux, I'd REALLY recommend getting IPython. It's the Python interactive interpreter souped up to a whole new level. Most of the code I write has this workflow:

- start IPython
- import some relevant libraries and modules or run -i thatscriptyouwereworkingon.py
- play around
- when you got something useful copy it to gedit (and save the script with .py extension for syntax highlighting)
- continue playing
- when needed run the .py script again with IPython's magic run command, preferably run -i because that way the script will be run in the interpreter's scope, and so you can access variables created by the script afterwards
- continue playing
- repeat until it's awesome

IPython does tab-completion, saves your past inputs *and* outputs in all sorts of handy arrays and variables. You get object inspection with name_of_the_object? and you get all sorts of useful info about its type and the doc string and where it was defined and such.

If you can also manage to get IPython's qtconsole running, you're in for even more treats. But that requires QT (which you probably have, it's a common GUI library, otherwise get it from the repo) and 0MQ aka ZMQ which you probably don't have and does not come as a binary package so you have to download its .tar.gz and build/install from source. If that sounds difficult, is okay, you'll only miss out on function argument tooltips, inline graphics and some other things, also slight buggyness because it's relatively new and experimental.

But really, DO get IPython.
Ex-Soviet Bloc Sexual Attack Swede of Tomorrow™
e-prime disclaimer: let it seem fairly unclear I understand the apparent subjectivity of the above statements. maybe.

INFORMATION SO POWERFUL, YOU ACTUALLY NEED LESS.

Rumckle

Awesome, thanks! I'll check it out this arvo
It's not trolling, it's just satire.

Triple Zero

(just posting this so I can clear the link from my open tabs :) )

Learn Python the Hard Way is a book that is free to read online as HTML (and can be bought in various ebook formats and probably dead tree as well).

I've heard many good things about it, even though I didn't really read it myself, since I'm not the target audience.

Part of the "thing" with the book is apparently that you're supposed to really *type out* the examples and exercises, not copy-paste them. Which I'm sure you'll agree definitely improves learning, though it might take a bit more effort.

Judging from the TOC it seems it will really take you for a full ride of all the fundamentals of Python. Including the bits that make it so damn awesome once you understand them, such as list comprehensions, generator expressions and decorators. Oh and of course classes and objects, I almost forget them cause they're so important I'd hesitate to call them "advanced" (fortunately they're not real difficult to grasp either, just pay real good attention when they get to the .__dict__ property, when you get that one, the rest is cake).

I'm also discovering that jEdit has a FUCKTON of plugins, and I'm betting I can tweak them until they make a really fine Python coding environment. But I will post about that later, when I have done so.
Ex-Soviet Bloc Sexual Attack Swede of Tomorrow™
e-prime disclaimer: let it seem fairly unclear I understand the apparent subjectivity of the above statements. maybe.

INFORMATION SO POWERFUL, YOU ACTUALLY NEED LESS.

Bu🤠ns


Triple Zero

Ex-Soviet Bloc Sexual Attack Swede of Tomorrow™
e-prime disclaimer: let it seem fairly unclear I understand the apparent subjectivity of the above statements. maybe.

INFORMATION SO POWERFUL, YOU ACTUALLY NEED LESS.

Bu🤠ns

http://sebsauvage.net/python/snyppets

I found that webpage useful for some random tips...also check out the http://sebsauvage.net/python main page for more.

Don Coyote

I think I'm going to start teaching myself python. Maybe I'll eventually be able to get Blender 2.61 to import/export a model format I need instead of janking around with an older version of Blender importing an older version of the model format.

Or Just I dunno. I could be fun.

Bu🤠ns

So I wrote a module to pull images from a tumblr blog and return their address to the bot on the IRC channel both randomly (command: !fy) and by tag query (command: !fy meryl streep).

Since I'm a total noob about Python, would anyone be willing to give it a critique? 

I'm looking for tips on keeping it simple and 'pythonic' (w/e that means).
Is there a better way to do certain things?
Style and module suggestions?


from util import hook
from random import choice
import re
import urllib2

'''
This molule uses the urllib2 module to open the fuckyeahdementia tumblr blog and retrieve random images. 
commands:
!fy  -- this will go to the random page and extract the random jpg
!fy <input> -- this will search the blog's tags for images. If it finds one, it posts it, if doesn't find one it will return 'Not Found' or 'Not Found', 404

'''

@hook.command("fy")  # hook command !fy
def fy(inp):
    if not inp:    # determines if there's a parameter or not if not, goes to the the random portion
        urlsource = urllib2.urlopen('http://fuckyeahdementia.com/random')    # Opens the page
        s = urlsource.read()    # reads the page
        image = re.search('pi:pinit:media="(.+)" pi:pinit:layout="', s)    # regex to extract the jpg address
        imagegroup = image.group(1)    # pulls out the jpg address from between the parenthesis, the (.+)
        return "!!Random!! ~(nsfw risk)~ " +imagegroup
    else:
        urlsource = urllib2.urlopen('http://fuckyeahdementia.com/')
        theurl = urlsource.geturl()    # geturl to pull the url only
        inp2 = inp.replace(" ", "-")    # the parameter for website reguries spaces to convert to "-"
        finalurl = (theurl) +"tagged/" +(inp2)    # Completes the url for the prameter search
        try:
            urlsource = urllib2.urlopen(finalurl)
            source = urlsource.read()
            finalimage = re.findall('pi:pinit:media="(.+)" pi:pinit:layout="', source)    # regex for finding the images and saving them to a list
            if finalimage == []:    # if finalimage list is empty return not found
                return "Not Found"
            else:
                randimage = choice(finalimage)    # randomly picks an item from the list and returns it
                return "NSFW risk: " +randimage 
        except IOError, e:
            if hasattr(e, 'code'):
                return "Not Found", e.code

Bu🤠ns

What is a Class? In plain terms, plz   :)

Telarus

In Object Oriented Programming, Classes can be thought of as abstract "templates" for Objects. It doesn't become an Object until you 'import' it into your current object-file, at which point the Class starts to setup default data/methods for the current Object. If another Class is imported after the first, it overwrites the previous default data.


So, for example, you could have a "Mammal" class, and then separate "Dog" & "Cat" classes, and then even a "Domesticated" class (which would overwrite some of the 'wild' data in the Dog and Cat classes), then you might have classes like "Farm Animal", "Hunting Companion" that could be applied to either Dogs or Cats and would override certain data in those archytypes.

Once it's all packaged up, it's an Object that you can query (i.e. is this Object a Mammal? Y/N Is this Object a Dog? Y/N etc, etc)

I hope that helps.
Telarus, KSC,
.__.  Keeper of the Contradictory Cephalopod, Zenarchist Swordsman,
(0o)  Tender to the Edible Zen Garden, Ratcheting Metallic Sex Doll of The End Times,
/||\   Episkopos of the Amorphous Dreams Cabal

Join the Doll Underground! Experience the Phantasmagorical Safari!

Triple Zero

That's all correct for the concept of classes in Object Oriented Programming, and sort of the case for classes in Python as well.

If you really want to.

But in Python, you usually don't. (good video. recommend watching)

Instead, if classes must be used in Python, use them for what they simply are. Which is a function. A special kind of function.

>>> # see, this is a function
... def aap(x=3):
...     print 'noot' * x
...
>>> # and if you call it, it works like this:
... aap()
nootnootnoot
>>> # and a function, like most things in Python is an object, which means you can do this:
... aap.mies = '774499'
>>> # what's that good for you ask? not much, it's just something you can do.
... print aap.mies
774499
>>> # also an object usually has a few other properties that it comes with. some are "special".
... # the "special" ones all start with __. for instance, a special property of nearly every object is __dict__:
... aap.__dict__
{'mies': '774499'}
>>> # neat huh? __dict__ shows you all properties in an object. except the ones that start with underscores
... # cause they're SECRET. a bit like hidden files, very useful to mess with, but kept out of sight.
... # another good one is __str__. that's a function that returns the string representation of the object.
... aap.__str__
<method-wrapper '__str__' of function object at 0x000000000909AF98>
>>> # yup that's a function (or method, same thing, nearly). let's call it!
... aap.__str__()
'<function aap at 0x000000000909AF98>'
>>> # that's the same thing you get if you'd write
... str(aap)
'<function aap at 0x000000000909AF98>'
>>> # okay now a class. I'm going to write it first then explain what happened.
>>> class Vrijdag(object):
...     def __init__(self, hoeveel=2):
...         print 'JEUMIG', hoeveel, 'DUIZEND VIS'
...         self.vis = ['baars', 'schol', 'haai'] * hoeveel
...     def vuur(self, wat='schol'):
...         welk = self.vis.index(wat)
...         self.vis[welk] = 'gebakken ' + self.vis[welk]
...     def __call__(self):
...         print 'HET ETEN IS KLAAR!!'
...         print 'WE HEBBEN'
...         for hap in self.vis:
...             print hap
...     def __str__(self):
...         return ' EN '.join(self.vis)
...     def __contains__(self, wat):
...         return (wat in self.vis) or ('gebakken ' + wat in self.vis)
...
>>> maal = Vrijdag(3)
JEUMIG 3 DUIZEND VIS
>>> maal.vuur()
>>> maal.vuur('baars')
>>> print maal
gebakken baars EN gebakken schol EN haai EN baars EN schol EN haai EN baars EN schol EN haai
>>> maal.vuur()
>>> print maal
gebakken baars EN gebakken schol EN haai EN baars EN gebakken schol EN haai EN baars EN schol EN haai
>>> if 'schol' in maal:
...     print 'JOEPIE SCHOL'
...     maal()
...
JOEPIE SCHOL
HET ETEN IS KLAAR!!
WE HEBBEN
gebakken baars
gebakken schol
haai
baars
gebakken schol
haai
baars
schol
haai


First there's the class definition. If you're using Python 3.x you can leave out the "(object)" bit. That's just for Python 2.x to signify we're using "new style" classes. The old style classes are obsolete and you shouldn't bother with them unless you like having obscure bugs because they work ever so slightly different than the new classes.

Okay now as you can see, a class in Python is sort of a function, with functions in it. And all the functions in it always have the first parameter named "self" (you can actually pick any name for that parameter but everybody and their pet python write "self", so just do that). In many other languages this parameter is named "this", btw.

Funny thing is, if you call such a method, the "self" parameter is implicit. You don't have to give it, it'll just contain the object on whcih the method was called.

That's (sort of) the difference between functions and methods btw. Methods are functions that are also properties of some object. And usually they have an implicit "self" parameter that tells the method what object it's being called on. That way the object can modify and inspect itself.

But I'm getting ahead of things. First, we call the class:

>>> maal = Vrijdag(3)
JEUMIG 3 DUIZEND VIS


Now what actually happened is that the special named method __init__ got called, with a new empty object as the self parameter. Then the __init__ method does some things to self, such as putting some things in self.vis. Then (implicitly) the return value of __init__ is always self, which is stored in the variable maal.

So now we got an object of type Vrijdag in the variable maal.

Then we call a method on this object:
>>> maal.vuur()

Which, as you can see at vuur's definition, modifies an element of self.vis. Very nice! We do it again, but now with a particular vis named baars instead of the default schol:

>>> maal.vuur('baars')

And now we're getting to the magic parts! What happens if we try to print our maal? Python will try to convert the Vrijdag object to a string, which is done by calling the special method name __str__ on that object. Which we redefined! And it works, look:

>>> print maal
gebakken baars EN gebakken schol EN haai EN baars EN gebakken schol EN haai EN baars EN schol EN haai


Brilliant! But there's more special methods! For instance, remember how you can check if an element is in a list by asking if 'no pun' in ten_did? But what if ten_did is not a list but some other object? Well, Python does not give up easily and checks if said object has a special method named __contains__, calls it with the thing we're looking for and sees whether that method returns True or False. That's why this works:

>>> if 'schol' in maal:
...     print 'JOEPIE SCHOL'
...     maal()


And that last line? You thought maal was an object, not a function? Yeah so? What happens if you call it? Well glad you asked, Python goes looking for the special method __call__ and calls that instead!!

So now we're back full circle, and you can see that a function is basically just an object with a __call__ method.

Oh and we can also simply access the vis property of our maal:

>>> maal.vis
['gebakken baars',
'gebakken schol',
'haai',
'baars',
'gebakken schol',
'haai',
'baars',
'schol',
'haai']


Basically, in Python, a class is just a thing that keeps methods and properties together in objects. So you can bundle them up, which is useful. And you can make them perform all sorts of nifty tricks by using the special method names.

BTW here you can find a list of all these special method names: http://docs.python.org/reference/datamodel.html#special-method-names

There's zillions of em. You can redefine what happens if you add objects together, or compare them, or redefine any operator such as the % or ** or >>

Did that help?
Ex-Soviet Bloc Sexual Attack Swede of Tomorrow™
e-prime disclaimer: let it seem fairly unclear I understand the apparent subjectivity of the above statements. maybe.

INFORMATION SO POWERFUL, YOU ACTUALLY NEED LESS.