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
Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Janin posted:

If the plugin metadata is stored in a documented format, it can be used to load a class that implements the documented interface, which is then used as a plugin. No dependence on an external registration library is needed.

This is an issue I ran into when trying to write a cleaned-up version of Screenlets. Each plugin loaded the library directly, and subclassed the main Screenlet class to auto-register. Thus, every plugin required the same version of the library to be active or it would fail to load. If they had used a separate metadata file, I could have parsed that file to determine which version of the libraries to provide.

Okay, I thought you meant sharing plugins between different applications, not different versions or instances of the same application, which would be troublesome with the metaclass approach.

Adbot
ADBOT LOVES YOU

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Janin posted:

There's not much difference, technically speaking, between different applications and very different versions of the same application.

True enough, but you could also add a class variable requires_version="1.0.1" to check in the metaclass. Of course add enough of those and at some point you do have a config file, just in a class instead of a file. . . .

Boblonius, I'd go with the code that Janin just provided. Metaclasses are fun and all but if you don't feel comfortable with them you shouldn't be using them yet. It would be easier to add error-checking to Janin's code than the metaclass code for you.

You should look into metaclasses though just because they're so much fun and will give you a better idea of how Python works.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Short answer: no. Long answer: yes, but only if the methods in the chain return self, which in the case of list is a (see Short Answer).

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Regular expressions? Seriously?
http://docs.python.org/library/csv.html#module-csv is probably the easiest.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Before 2.6 I did
code:
def prop(f):
   fget, fset, fdel = f()
   return property(fget=fget, fset=fset, fdel=fdel, doc=f.__doc__)
and in a class

code:
...
    @prop
    def f(): # NOTA BENE: lack of self argument
        "lorem ipsum"
        def fget(self): #self here, though
            return self.whaeva
        ... etc ...
        return fget, fset, None # returning None disables a feature
...
But if you have Python 2.6, do what Tef said. In fact, all of you do what Tef says or my crew will jump you.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
It looks like it's running fine except you didn't pass it any command line arguments and you're running it on windows instead of a *nix. There does not appear to be a problem. What do you think is wrong?

Try running it from the command line like
code:
python using_sys.py We are arguments

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
code:
for i, v in enumerate(t):
    print i, "; ", v
outputs
0: . . .
1: . . .
2: . . .

and so on

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
With any luck Nokia's PySide, a recreation of PyQT, will ameliorate those horrors, as QT itself is fantastic and it would be nice to use in Python without dumb poo poo like that, but PySide is new and it's going to be a while before they even start to make the interface pythonic. :(

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Thermopyle posted:

It's entirely possible that I'm not using objects right, but...

Is it possible for an class to return a value instead of an object when it's instantiated?

For example, I've got a Film class that tries to determine which movie a file is. When I instantiate the object it parses the filename and uses the API for TMDB to determine if it's got the movie name figured out and then returns an object with title, year, actors, etc.

I'd like the object to just return None or False if it thinks it's not actually a movie.

Of course, I could just set an attribute on the object and then check that attribute later, but I'm mainly just curious if this is possible or if I'm thinking about classes/objects the wrong way.

No, that's not possible. Yes, it sounds like you are not using objects right. It sounds like you want is a function that returns a Film object iff it is constructible.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Hmm, I suppose so but it's also technically possible to shoot yourself in the face. I wouldn't recommend either, except in special circumstances.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

echinopsis posted:

so that's my attempt using lists but I must fundamentally misunderstand something as it complains that I am indexing out of range whenever I got toy[i] something (and i=>1).. what is wrong with me

code:
import random
toy=[range(len(target))]
This creates a list of one element which is the list returned by range.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Thermopyle posted:

What's a good heuristic for figuring out whether something would be better as a method or a function?

Is it an intrinsic action on the abstraction itself or is it an action that uses the abstraction? That's what I use.

In your specific case, it seems that you want that function to be __init__ unless there are several ways to create the object in which case several such factory functions is the way to go.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
In Python 3+, print is a function not statement so its arguments need to be wrapped in ()

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
I only have a minute but just glancing at it there are exactly zero reasons that should be a class and uncountably infinitely many why it shouldn't be. Other than that :wtf: it looks fine, but like I said I just did it a cursory once over.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
if you replace sum(i, total) with i + total it will work. As it is sum(args) will work as you intend. Further, there is no reason for a while loop here. Tuples are iterable.

Edit: if you're not trying this stuff out in the python shell, you're doing it wrong.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

quote:

Traceback (most recent call last):
File "ex12_1.py", line 9, in <module>
sum_all(1, 2, 3)
File "ex12_1.py", line 6, in sum_all
total = sum(args[i], total)
TypeError: 'int' object is not iterable

You need to learn to read these. It says your sum_all function was called and inside it an error happened on line 6 where you call sum. So you open up the interactive interpreter and try a few things until you get to sum(1, 2) and see that that is the error.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
import atexit

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Assuming that that is your complete file, the first global isn't doing anything. You just need it in function bodies. But try to eschew global state.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Stabby McDamage posted:

I'd say namespace pollution is a big reason.

If I want 20 numpy functions, I either (a) request each of them by name, (b) preface each of them with numpy. (or numpy.linalg. or numpy.somethingelse.), or (c) import *, which fills my namespace with a bazillion things.

Now, plain functions make sense for 2+ variable operations like dot product (nobody wants to see javabortions like a.dotproduct(b)), but for single-input calculations, a.norm() makes sense.

The class is a namespace too :mad:

a.norm() is as nonsensical as a.dotproduct(b) :confused:

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

nbv4 posted:

All though, I think that syntax is 2.6/3.x only.

2.5+, I believe

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Read about the global keyword

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Teaching OO anything to someone at that level is useless at best and destructive at worst. Let him get to the point where he has a program that could benefit from OO, not just scream BEST PRACTICE! and make him throw a bunch of stuff that makes no sense in his program.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
global not globals()

Having a few global variables in an incredibly small program that runs once and then dies is hardly a hack.

Better ways to structure code can be explored after he has the satisfaction of getting something working, but baby steps.

Systran, get something to work. Let it be ugly. When you're sure it works, figure out ways to clean it up and keep asking questions.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Modern Pragmatist posted:

Although a singleton is a safer and more OO approach to a global variable, I still feel that there are very few situations that would warrant the use of either of these.

Its just that I have yet to run into a situation where I can't refactor my code to avoid using globals. Conversely, I have run into many headaches when dealing with others' code that relies upon globals.

While a singleton is certainly more OO it is not inherently more or less safe. It's the same thing with a different name.

I gave a use for globals: short programs that run one and then quit, which I had thought systran's code was.

You can certainly refactor globals away. The question is, is it worth the added complexity? On the other hand, globals are like gotos. Generally to be avoided but if it's simpler to use it, use it. Furthermore, in the context of someone new to programming, refactoring code and data flows to avoid global state is hardly justifiable. If you show them how to do it without showing them why or letting them learn why, then you get a coder who codes by dogma not experience and reason.

The reason code with gotos and globals get a bad rap is because most of it is written by people who leap to them unreflexively without weighing the consequences or alternatives first. But bad code is bad code. That doesn't mean that the ingridients of bad code are themselves inherently bad. Bad code has plenty of if statements as well, after all.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
isa = isinstance

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Dictionaries are unordered. If you want to preserve order you can do a list of tuples but you'll have to search every element in the list and compare to the first element of the tuple which is significantly more work.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
That's a valid use of a file object, just not what he intended. If you use a file object as an iterator it defaults to readlines so your code could be expressed more simply as:

code:
word_list = open("wordlist.txt", "r")
words = [line.strip() for line in word_list]

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

sund posted:

You'll need to use enumerate() if you want to do it that way, because "line" isn't the index of the line, it refers to the line itself. Here you are with slicing:

code:
myMovies = open('movieList.txt','r')
for line in myMovies[8:]:
    print line

You need to use islice or read the whole file into memory with readlines and then slice it:

code:
from itertools import islice
myMovies = open('movieList.txt','r')
for line in islice(myMovies, 8, None):
    print line
or
code:
myMovies = open('movieList.txt','r')
for line in myMovies.readlines()[8:]:
    print line

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
It is still evaluated left to right:
code:
def M(s):
     def f():
          print s
          return 0
     return f
one, two, three = [M(n) for n in "one two three".split()]

>> one() <= two() <= three()
one
two
three
>> 
In a < b < c it evaluate a < b and returns false if a >= b but if it's true then it moves on and tries b < c, so it essentially expands it into a < b && b < c for you

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
code:
def parse_duration(value):
    t = re.search()#same but with <names> changed to those in d & timedelta
    d = {"hours":0, "minutes":0, "seconds":0, "milliseconds":0}
    if t:
        d.update(t.groupdict())
    return datetime.timedelta(**d)
think you can alternately pass d to groupdict, but the documentation wasn't entirely clear and I didn't feel like testing it

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
You are passing it two and it only accepts one. The first parameter of a method is the object so a.b() is the same as b(a) so a.b(c) is b(a, c).

So you need to change your method to take (self, genome).

also it's __init__ not init so it should be __init__(self, genome)

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
use `enumerate`

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
== : any X any -> bool. You don't need == True. Also If and if are different things as far as Python knows. Are you trying to find out if the type of a variable's value is int or are you trying to determine if a value is integral? Those are two very different things and everyone is answering the former question.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.

Stabby McDamage posted:

It's just that this is one of the most common file operations ever

Really? I have never once had any reason to do that. What do you do where this is so incredibly common? Also since we're giving smartass answers open is the most common file operation ever.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Why would you jump through all those hoops instead of just having a dict of functions :psyduck:

Adbot
ADBOT LOVES YOU

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Yes, threads are not completely free. You'd get a better improvement by splitting the files up into n batches each processed by n threads where each thread processes each of the files in its batch serially.

  • Locked thread