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
JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Lurchington posted:

Is there a list of characters that are illegal in at least one filesystem? I'm fine with losing some possibly legit characters in the crossfire for at least the first go.

You probably want to stick to vfat, since it's still used as a portable file system: http://averstak.tripod.com/fatdox/names.htm

You definitely want to avoid :, / and \ since they're used as directory separators on Mac, Unix and Windows respectively. (Actually this is the obsolete usage for Mac, now it uses /, but I think it still supports it or tries to convert or something - safest to ignore it.) Conveniently those aren't in that list anyway.

I would also recommend avoiding ! since it messes with the escaping rules on Linux. (It can still be escaped, it's just a hassle.)

Adbot
ADBOT LOVES YOU

Bozart
Oct 28, 2006

Give me the finger.

Lurchington posted:

Which I'm fine with doing as long as I know which characters are illegal, which I thought was the issue. I need to investigate OSError, but will that report which characters are illegal?

Is there a list of characters that are illegal in at least one filesystem? I'm fine with losing some possibly legit characters in the crossfire for at least the first go.

code:
import re

def GoodFileName(Name)
    p = re.compile( '\W+')
    return p.sub('_', Name)
I mean, this is a really stupid way to do this but I am pretty sure it works in any filesystem.

Bozart fucked around with this message at 15:26 on Oct 14, 2008

Lurchington
Jan 2, 2003

Forums Dragoon
non-alphanumeric catches too much I think. Apostrophe's and commas, parentheses all come up a lot and hurt readability if I nail them.

thanks for the response, it forced me to think of the non-alphanumerics I care about.

And thanks for the link to the vfat restriction, I think that will be my first go, and on OSError pop a dialog.

Lurchington
Jan 2, 2003

Forums Dragoon
So, let's talk Editors and IDEs (possibly again).

Due to my work situation, I'm working with three main IDEs:

IDLE (comes with your installation). Perfectly fine, and if it wasn't for the inability to use tabs I'd probably make it work still.
    Cons (in my experience):
  • Difficulty running a program with command line arguments
  • Doesn't play nice with GUI toolkits like wxPython
  • Aforementioned lack of tabs means that there will be a lot of open windows around if you move beyond the scripting level
    Pros:
  • It's available anywhere, so it's a good idea to familiarize yourself with it
  • Unlike a straight editor you can run your script directly.
  • The baseline from which all other comparison are made.

PyScripter (windows only as far as I know). My first IDE outside of IDLE and I was initially impressed with the presentation and usability. However, after using it more often I've uncovered a few serious gotchas that can actually make you lose time.
    Cons (in my experience):
  • The internal python interpreter does a lot of pre-caching to provide you with all the call tips and tab completion options. Unfortunately that means that if you change code in another module you're going to need to manually refresh things for it to work. I think that using RUN -> import module on the module you just edited works ok, but I forget, and I've definitely restarted the whole thing just to ensure it works.
  • The internal python interpreter has trouble running modules that are part of a package (as in there's an __init__.py file in the directory). The included unit test runner (which I like a lot) has this problem too. And eventually I just removed the __init__.py when developing on PyScripter, since there's no issue when I use PyScripter's external interpreter, or another IDE.
  • Finding, and Find-and-Replace is pretty clunky compared to other editors. I've repeated operations on accident, and I've deleted things trying to go to the next instance.
  • I can't undo past a save. So if I save as a habit after writing some new code, then run to discover a typo, I can't undo it. An inconvenience, but not as bad
    Pros:
  • Doesn't need administrator privileges to install as long as you install it to where you have write access. However, it places a preference file in C:/ (possible the top level of whatever drive letter you're on) no matter what.
  • The aforementioned unit test runner is really quite nice, and automatically parses the TestCases you write to work with built-in unittest. However, if you use logging during your unit tests, it won't display unless you run you're module normally.
  • Code exploration view (eg, class attributes and methods), call tips and tab completion options are filled out very intelligently, and almost makes for the difficulties in getting everything working right when you update something.
  • ability to specify, and save, command line arguments
  • I like the layout a lot, includes tabs, and has a place for all the stuff I care about. It can feel a bit stuffed if you're using it on a 1280x1024 monitor though.

Stani's Python Editor (SPE) (written in Python, and cross platform). Probably my preferred environment now after switching to full-time development on OSX and Ubuntu. Visually very similar to PyScripter and has a lot of the same usability enhancements.
    Cons (in my experience):
  • Very slow using the internal interpreter if you didn't get a binary executable for your operating system. Both OSX and Ubuntu had very easily found versions, but I couldn't find one for windows, and that's made it kind of unusable. The external interpreter works as long as you have it set up write, but I've still shied away from it.
  • I got very used to PyScripter's unit test runner, and there's no equivalent
  • The tab completion options pull from the built-ins and what's been entered in the current module. So if you type in "module.typoz" that will stay as a valid tab-complete option even if you delete it and continue to write module.typo. Basically the tab-complete is dynamic, versus PyScripter's pre-compiled.
  • I donated, and the manual I received wasn't all that helpful. Also, I've been unable to get the please donate stuff of my IDE and to get the help area to point to the manual

    Pros:
  • Support for a lot of plugins and third-party utilities. In the menu structure you can interact with blender, wxglade, and a lot of other things. On Ubuntu it will download those as part of the SPE package.
  • All the usability stuff that PyScripter has as far as command line, tab complete, call tips. Plus a LOT more stuff I'm not familiar enough to use.
  • built-in docstring compiler and UML drawing based on your code (very basic UML, but still nice)
  • if you don't donate you're not missing any features at all

I was bored and got into work earlier than normal.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Have you tried out Eclipse+PyDev?

I just want textmate to have code completion. That's all I want.

Lurchington
Jan 2, 2003

Forums Dragoon
No, and I can honestly say I was scared off because I have irrational fear of anything related to Java. Emphasis on irrational.

Bozart
Oct 28, 2006

Give me the finger.

Lurchington posted:

So, let's talk Editors and IDEs (possibly again).

Stani's Python Editor (SPE) (written in Python, and cross platform). Probably my preferred environment now after switching to full-time development on OSX and Ubuntu
....

I gotta say that after messing around with python stuff in windows and getting fed up with mingw and other bullshit, it was an absolute breeze to install ubuntu on my spare computer, install spe, and good to go with everything.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Lurchington posted:

No, and I can honestly say I was scared off because I have irrational fear of anything related to Java. Emphasis on irrational.

I'd give it a try: It helps out quite a bit and is actually pretty nice - my biggest beef with it is that it is "AN IDE", and I'm more of a minimalist. That, and I can't figure out how to change the color that pydev uses when it highlights all occurrences of a symbol in the current file.

GuyGizmo
Feb 26, 2003

stupid babies need the most attention
I'm still fairly new to Python, and I'm working on writing a module that needs to dynamically discover and import its own submodules.

Basically, the structure of it looks something like this, and I'll use the names here in place of the actual names of the module I'm writing for simplicity:

Module/
- script1.py
- script2.py
- Thingies/
- - thing1.py
- - thing2.py
- - thing3.py
- - thing4.py
- - ...

There's two things I'd like to do here, and I'm not sure how I'm supposed to go about and do them. First, I'd like script1.py and script2.py to be able to get a list of the existing scripts in Module.Thingies, and dynamically import one of them and call functions in it. Second, I want all the scripts in Thingies to be able to import and call functions from script1.py and script2.py. I haven't gotten it to work, though.

I tried using dir(Thingies) to get a list of submodules containined within it, but it only works once the entirety of Thingies has been imported, which means prefacing either script1.py or script2.py with 'from Thingies import *'. But whenever I do that, thing?.py will throw an ImportError when I try to have it import either script1.py or script2.py using something like 'from .. import thing1.py'. I think it has something to do with having thing1.py import script1.py that imports thing1.py again, but I don't know how to work around it.

What am I supposed to do here to get that to work?

BlackDiamonds
Mar 15, 2007

GuyGizmo posted:

What am I supposed to do here to get that to work?

Place an empty text file titled __init__.py in the Thingies folder. For more information look up on python modules and python packages.

GuyGizmo
Feb 26, 2003

stupid babies need the most attention

BlackDiamonds posted:

Place an empty text file titled __init__.py in the Thingies folder. For more information look up on python modules and python packages.

Actually I did do that already, so it's not the solution here.

Also, here's the error specifically that I'm getting:
code:
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import Module.script1
  File "script1.py", line 2, in <module>
    from Thingies import *
  File "Thingies/thing1.py", line 2, in <module>
    from .. import script2
  File "script2.py", line 2, in <module>
    from Thingies import *
  File "Thingies/thing2.py", line 2, in <module>
    from .. import script1
ImportError: cannot import name script1
Right now I'm looking into the correct way to dynamically load a submodule so that I don't need the 'from Thingies import *' anymore. That still doesn't help with how I figure out all of the existing submodules in Thingy, though, because dir() doesn't work unless I import them all.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
GuyGizmo - here's something I used a long time ago - I haven't looked at this recipe since I uploaded it, and I know (knowing as much as I know now) it could be improved. Maybe it helps.

http://code.activestate.com/recipes/436873/

drat, that was 3 years and 3 months ago.

GuyGizmo
Feb 26, 2003

stupid babies need the most attention
I think I finally got it. The key seems to be that python just doesn't like circular import statements, so if I load the module I need dynamically it works. I ended up having to do something obtuse like:
code:
submoduleName = "thing1" # or something
mainModule = __import__('thingies', globals(), locals(), [submoduleName], -1)
exec "submodule = mainModule." + submoduleName

submodule.function()
As for finding out which submodules exist, I can just do what they did in the link m0nk3yz posted and just use os.listdir to get a list of python source files.

Thanks for the help everyone.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

GuyGizmo posted:

I think I finally got it. The key seems to be that python just doesn't like circular import statements ...

Late to the dance, but this is a point that needs underlining. As opposed to (say) C, where you pay great attention to where and in what order things are included, in Python this _largely_ disappears. I say largely, because circular imports can create all sorts of cryptic errors that are hard to diagnose. The moral: decompose your design properly, so you don't end up with modules calling each other.

As for you above problem, I once had to solve something similar and ended up with this: a file (e.g. thing1.py) finds out its own path. Use that to get it's parent directory. List and select the files in that directory. Import doesn't come into it.

duck monster
Dec 15, 2004

Trying to get Python Imaging Library working with python on Os/X has got me very loving close to just abandoning developing on macs :(

It shouldnt be this hard, but it is, and the fact that Apples primitive-rear end packaging system (there isnt one) is somewhere around "Slackware in the early 90s" doesnt help at all.

Everything on google says to either use fink or macpython. no no no no no I'm not using THAT python, I want to use THIS python that came with it.

Argh.

Come on Apple, just put one staffer onto maintaining your python distro. Its all it will take! You cant just throw products out the door pre-abandoned.

</rant>

Seriously Apple should just annoint APT-GET or portage or something and provide official distros of stuff like mysql and the python libs and poo poo, so this primitive rear end nonsense of having to hand patch poo poo all the time to get it to compile is history. God forbid someone wanting to run a mac as a server, and having to deal with security updates to open source software.

dagard
Mar 31, 2005
(Please be kind: I'm normally a perl guy, and just dipping toes in this)

Lets say I have a set: [1, 'hi', 38, 'oh hello there'] called ARGL

I'm trying to figure out how to do the python version of:

OBJECT->method("something", @ARGL)
so that OBJECT->method would be called with, effectively:

OBJECT->method("something", 1, "hi", 38, "oh hello there")

Right now, when I call OBJECT.method("something", ARGL), naturally, it complains, as method() wants more arguments than i'm sending it.

I'm missing something blindingly obvious, aren't i?

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

duck monster posted:

Trying to get Python Imaging Library working with python on Os/X has got me very loving close to just abandoning developing on macs :(

Adding to the list of "yeah, I had this problem too", you might wants to look at my notes on installing PIL, to see if there is any help there.

To be fair, it's not all Apple's fault, the PIL installer is a little odd. Again, image handling is something that should be in the standard library.

hey mom its 420
May 12, 2007

code:
>>> foo = [1, "two", "foo", "bar"]
>>> def f(arg1, arg2, arg3, arg4, arg5):
...   print "arg1 is:", arg1
...   print "arg2 is:", arg2
...   print "arg3 is:", arg3
...   print "arg4 is:", arg4
...   print "arg5 is:", arg5
...
>>> f("something", *foo)
arg1 is: something
arg2 is: 1
arg3 is: two
arg4 is: foo
arg5 is: bar
The key is the *.

uncleTomOfFinland
May 25, 2008

dagard posted:

(Please be kind: I'm normally a perl guy, and just dipping toes in this)

Lets say I have a set: [1, 'hi', 38, 'oh hello there'] called ARGL

I'm trying to figure out how to do the python version of:

OBJECT->method("something", @ARGL)
so that OBJECT->method would be called with, effectively:

OBJECT->method("something", 1, "hi", 38, "oh hello there")

Right now, when I call OBJECT.method("something", ARGL), naturally, it complains, as method() wants more arguments than i'm sending it.

I'm missing something blindingly obvious, aren't i?

You mean something like this?

EDIT: Should always F5 threads I have had open for a while. :(

code:
def checkthisout(x, y, z):
    print x, y, z

>>> checkthisout(1,(2,3))

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    checkthisout(1,(2,3))
TypeError: checkthisout() takes exactly 3 arguments (2 given)

[b]>>> checkthisout(1, *(2,3))
1 2 3[/b]

tef
May 30, 2004

-> some l-system crap ->

dagard posted:

I'm missing something blindingly obvious, aren't i?

http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

As mentioned already, you can use *foo to unpack the arguments.

What hasn't been mentioned is that you can use it in function definitions:

code:
def foo(*args):
    pass

Calling foo(1) sets args to [1], foo(1,2,3) sets args to [1,2,3], and so on.
There is an equivilent operator for dictionaries **.

Lurchington
Jan 2, 2003

Forums Dragoon
it may make sense already, but if you're using both the list and dictionary unpack in a function definition, the order is important.

code:
def foo(*args, **kwargs):
    pass
this mirrors the convention of never being able to call foo(arg1, arg2, arg3="test", arg4)

I've kind of shied away from dictionary unpacking since programming in python, but your mileage may vary.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Lurchington posted:

non-alphanumeric catches too much I think. Apostrophe's and commas, parentheses all come up a lot and hurt readability if I nail them.

thanks for the response, it forced me to think of the non-alphanumerics I care about.

And thanks for the link to the vfat restriction, I think that will be my first go, and on OSError pop a dialog.

a good way to get rid of random unicode characters while keeping some of their meaning is to use Unicode Normalization, normalize to form KD then strip any unicode character (I use a regex but you can also use .encode('ascii', 'ignore') ). What normal form KD does is decompose a unicode character into it's component characters. So for example ņ becomes n and \x0303 (non-spacing tilde above), when printing they occupy the same space but in the character array they are two indices apart, thus if you run it through a regex it may leave you with only ascii characters.

Quick couple lines:
code:
from unicodedata import normalize
x = u'coņo'
y = normalize('NFKD', x).encode('ascii','ignore')
>>> print y
"cono"
I call this lossy unicode normalization and I use it for readable URLs. Also, I am not sure this works at all with languages that don't use the latin characters.

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

[st]Newb question, whats the logic behind if __name__ == '__main__'? It seems like some kind of way to test code but I can't quite work it out :([/st]

cancel that, I've worked it out!

LuckySevens fucked around with this message at 09:22 on Oct 17, 2008

bitprophet
Jul 22, 2004
Taco Defender

LuckySevens posted:

[st]Newb question, whats the logic behind if __name__ == '__main__'? It seems like some kind of way to test code but I can't quite work it out :([/st]

cancel that, I've worked it out!

Protip: never just say "nm I got it!" -- explain what you found / how you solved your problem! Otherwise another newb finding your question on Google or whatever, and not seeing an actual answer, is going to hate your guts :)

Lurchington
Jan 2, 2003

Forums Dragoon

deimos posted:

a good way to get rid of random unicode characters while keeping some of their meaning is to use Unicode Normalization, normalize to form KD then strip any unicode character (I use a regex but you can also use .encode('ascii', 'ignore') ). What normal form KD does is decompose a unicode character into it's component characters. So for example ņ becomes n and \x0303 (non-spacing tilde above), when printing they occupy the same space but in the character array they are two indices apart, thus if you run it through a regex it may leave you with only ascii characters.

Quick couple lines:
code:
from unicodedata import normalize
x = u'coņo'
y = normalize('NFKD', x).encode('ascii','ignore')
>>> print y
"cono"
I call this lossy unicode normalization and I use it for readable URLs. Also, I am not sure this works at all with languages that don't use the latin characters.

Thanks a lot. This is a much better way of doing it than my previous method.

Lurchington
Jan 2, 2003

Forums Dragoon
I think I abstracted myself one too many layers with my data class that I made (basically, I want to always interact with it a certain way, but I don't want to always be stuck using shelve).

This code fragment will show the contents as staying in the state I initialized it, and neither of the assignment statements I wrote do anything.

code:
            if showname not in self.data:
                logging.debug("initializing showname: %s", showname)
                self.data[showname] = {}

            logging.debug("prepped data %s", prepped_data)
            logging.debug("inferred_search: %s", inferred_search)

            # Neither of these statements work
            self.data[showname].update({inferred_search:prepped_data})
            ##self.data[showname][inferred_search] = prepped_data

            logging.debug("show contents: %s",self.data[showname])
            logging.debug(self.data[showname][inferred_search])
here is the definition for the self.data class.

code:
class TvDbData:
    def __init__(self, data_path=""):
        """
        Class for interacting with TvDb data
        """

        self.data_path = data_path
        self.open()

    def open(self):
        """
        Opens all data resources for later interaction
        """

        self.data = shelve.open(pjoin(self.data_path,"tvdb_data.cache"),"c")
        self.seriesid = anydbm.open(pjoin(self.data_path,"tvdb_id.map"),"c")

    def set_data(self, showname, value):
        """
        Shelves the value to key: <showname>, then syncs the shelf
        """

        self.data[self._cast_string(showname)] = value
        self.data.sync()

    def get_data(self, showname):
        """
        Returns the the value associated with showname. Can throw a
        KeyError on invalid showname
        """

        return self.data[self._cast_string(showname)]

    def __contains__(self, showname):
        """
        overloads in operator for testing the presence of a showname
        """

        return self._cast_string(showname) in self.data

    def __getitem__(self, showname):
        """
        Currently overloads get_data
        """

        return self.get_data(self._cast_string(showname))

    def __setitem__(self, showname, value):
        """
        Currently overloads set_data
        """

        return self.set_data(showname,value)

    def _cast_string(self, text):
        """
        used to ensure that unicode is encoded as a string for interaction
        with shelve and anydbm which require it
        """

        if isinstance(text,unicode):
            return text.encode("UTF-8")
        else:
            return text
I'm thinking that I'm returning only the value of the key it wants, instead of the actual contents of the key (in c++ terms, I return the value, not the pointer)

Thoughts?

I get as output:

DEBUG: prepped_data = {blah, valid dictionary}
DEBUG: inferred_search = "valid string"
DEBUG: show contents: {}
then a KeyError on logging.debug(self.data[showname][inferred_search])

thanks for any thoughts on this one

SlightlyMadman
Jan 14, 2005

Is there a way I can get a list of all the objects defined in an import? I'd like to be able to do something like:

code:
import foo_lib

foo_objects = get_all_objects(foo_lib)
foos = []

for foo in foo_objects:
    foos.append(getattr(foo_lib, foo)())

Allie
Jan 17, 2004

vars(foo_lib)

Works on any object except those with __slots__.

MononcQc
May 29, 2007

I'm going to work on making myself a website in python with web.py (didn't like the heavier nature of django all that much), but I'd like to be able to migrate from python 2.5 to 2.6 to then go on 3.0 when/if the framework supports it.

I'm currently testing stuff out with apache and mod_wsgi, which needs to be reinstalled anytime you switch version, and googlecode page only talks about support from python 2.3 to 2.5.

Am I better off switching to lighttpd? I don't exactly know how switching versions is done there. What would be the best way to do things?

Also, what would be the best framework to work with to get fast support for newer versions of python? I do like web.py as stated above and would like to stick with it, but I guess I could go back and try django some more if it fits the needs better.

SlightlyMadman
Jan 14, 2005

Milde posted:

vars(foo_lib)

Works on any object except those with __slots__.

Sorry, I should have written that import line as:
code:
from foo_lib import *
Basically, there's a file (foo_lib.py) that has multiple classes defined in it, and I want to instantiate them all and put them in a list.

edit: I want something similar to sys.modules, except instead of iterating all modules loaded, I want to iterate all classes loaded in a particular module.

edit 2: Ah-ha! Checking out vars() got me where I needed to go, though. Here's the code I came up with:

code:
import types
from foo_lib import *

all_vars = vars(sys.modules["foo_lib"])
for var in all_vars:
	var_type = type(all_vars[var])
	if var_type is types.TypeType:
		print var
So far, there hasn't been a single thing I've wanted to do in python, that I couldn't.

SlightlyMadman fucked around with this message at 16:18 on Oct 22, 2008

Colorblind Pilot
Dec 29, 2006
Enageg!1
Let's say I have a function and variable defined like this

code:
def this_is_a_test():
  print "LOL!"

x = "is_a_test"
Is there any way to call my function by calling "this_" + x()

basically dynamically constructing the name of my function based on the variable x? I know it can be done in Ruby, but it would make my life a lot easier if Python could do it too.

bitprophet
Jul 22, 2004
Taco Defender

Colorblind Pilot posted:

Let's say I have a function and variable defined like this

code:
def this_is_a_test():
  print "LOL!"

x = "is_a_test"
Is there any way to call my function by calling "this_" + x()

basically dynamically constructing the name of my function based on the variable x? I know it can be done in Ruby, but it would make my life a lot easier if Python could do it too.

It can be done, but that sort of "clever" programming is generally discouraged because it makes for difficult to debug / understand code (not to mention making bugs a lot more likely).

Offhand I'd do it like this:
code:
def this_is_a_test():
    print "LOL!"
x = "is_a_test"
locals()['this_' + x]()
since locals() returns a mapping of the local namespace.

EDIT: Like the below post, I'd say a more transparent and less problem-prone approach would be to explicitly organize the methods in a dict or other data structure, since it's easy to toss around functions as objects.

bitprophet fucked around with this message at 04:02 on Oct 23, 2008

Allie
Jan 17, 2004

What are you trying to do? If you're trying to do dispatch based on some kind of input, I'd make a dict mapping strings to functions.

If that's too tedious for whatever reason, you could make a lookup function in the same module that uses something like globals()['this_' + x]. If the functions are actually methods, you could use getattr(self, 'this_' + x). I don't know that that's necessarily good style or form though.

Colorblind Pilot
Dec 29, 2006
Enageg!1

Milde posted:

What are you trying to do? If you're trying to do dispatch based on some kind of input, I'd make a dict mapping strings to functions.

How do you make a dict map strings to functions?

Milde posted:

If the functions are actually methods, you could use getattr(self, 'this_' + x). I don't know that that's necessarily good style or form though

Why is that not good style or form? This chapter of Dive Into Python seems to suggest it's fine: http://www.diveintopython.org/power_of_introspection/getattr.html#d0e9362

Colorblind Pilot fucked around with this message at 06:01 on Oct 23, 2008

hey mom its 420
May 12, 2007

Python supports functions as first-class objects. So one way to do it would be this.
code:
>>> def foo(x):
...   print 'haha %s' % x
...
>>> def bar():
...   print 'hoho'
...
>>> my_func_dict = {'the_foo':foo, 'the_bar':bar}
>>> my_func_dict['the_foo']('blah')
haha blah

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
A better example would be to modify bar() to also take an argument. Usually, if dispatching is through a dictionary functions should have compatible signatures.

hey mom its 420
May 12, 2007

Yeah, that's true.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
I often find something like this useful:

code:
>>> dispatcher = {}

>>> def dispatch(table):
...     def decorator(f):
...         table[f.__name__] = f
...         return f
...     return decorator

>>> @dispatch(dispatcher)
>>> def foo(x):
...     print 'haha', x

>>> dispatcher['foo']('blah')
haha blah

nbv4
Aug 21, 2002

by Duchess Gummybuns
hi i'm learning how to do python. whats the way to do this:

code:
for field in ["att1", "att2", "att3"]: #this is a list of attributes of the object
	if object.field == 0:
		object.field = ""
basically i want to go through a bunch of attributes on an object and change them to "" when they are 0. The problem is accessing the attributes from the variable "field"

Adbot
ADBOT LOVES YOU

hey mom its 420
May 12, 2007

code:
for field in ["att1", "att2", "att3"]:
  if getattr(object, field) == 0:
    setattr(object, field, "")

  • Locked thread