0

If I have different functions with increasing numbers in their names how do I loop through them? For example:

def Func1():
    something something

def Func2():
    something something

def Func3():
    something something

...

def Func456832():
    something something

def Func456833():
    something something

How can I loop through them with a:

for i in range(1,456833):

In essence it's this question: How do I loop through functions with a for loop?

Edit: Because so many asked, this is my real code:

def write(self):
    with open('distances.txt', 'a') as file:
        file.write('\n'+str(self.distance1))
        file.write('\n'+str(self.distance2))
        file.write('\n'+str(self.distance3))
        file.write('\n'+str(self.distance4))
        file.write('\n'+str(self.distance5))
        file.write('\n'+str(self.distance6))
        file.write('\n'+str(self.distance7))
        file.write('\n'+str(self.distance8))
        file.write('\n'+str(self.distance9))
        file.write('\n'+str(self.distance10))
        file.write('\n'+str(self.distance11))
        file.write('\n'+str(self.distance12))
        file.write('\n'+str(self.distance13))
        file.write('\n'+str(self.distance14))
        file.write('\n'+str(self.distance15))

I realised this was a pretty shitty way of getting it done, especialy if I wanted to keep expanding the list. So I went looking for the answer and this seemed to be what I needed to know in order to fix it.

Edit2: Where I get the self.distanceX from:

class NeuralNetwork():
     def __init__(self, inputs, hidden1, hidden2, hidden3, outputs, alpha,it_1,it_2,it_3,it_4,it_5):

    ....

    self.distance1 = [alpha,hidden1,it_1,'train',0,0,0,0,0]
    self.distance2 = [alpha,hidden1,it_1,'test',0,0,0,0,0]
    self.distance3 = [alpha,hidden1,it_1,'dist',0,0,0,0,0]
    self.distance4 = [alpha,hidden1,it_2,'train',0,0,0,0,0]
    self.distance5 = [alpha,hidden1,it_2,'test',0,0,0,0,0]
    self.distance6 = [alpha,hidden1,it_2,'dist',0,0,0,0,0]
    self.distance7 = [alpha,hidden1,it_3,'train',0,0,0,0,0]
    self.distance8 = [alpha,hidden1,it_3,'test',0,0,0,0,0]
    self.distance9 = [alpha,hidden1,it_3,'dist',0,0,0,0,0]
    self.distance10 = [alpha,hidden1,it_4,'train',0,0,0,0,0]
    self.distance11 = [alpha,hidden1,it_4,'test',0,0,0,0,0]
    self.distance12 = [alpha,hidden1,it_4,'dist',0,0,0,0,0]
    self.distance13 = [alpha,hidden1,it_5,'train',0,0,0,0,0]
    self.distance14 = [alpha,hidden1,it_5,'test',0,0,0,0,0]
    self.distance15 = [alpha,hidden1,it_5,'dist',0,0,0,0,0]

Edit: solved. Thanks everyone :)

10
  • 2
    Is there any reason you have (it seems) 456833 functions rather than a single function with an extra parameter? Commented Apr 18, 2017 at 17:10
  • 5
    This feels like an XY problem to me. What are you trying to accomplish by doing this? Commented Apr 18, 2017 at 17:13
  • 2
    What you're asking for is help implementing a pretty bad practice. What problem are you trying to solve which this fixes? Commented Apr 18, 2017 at 17:13
  • 1
    @TemporalWolf - it depends... unittest runs tests by finding classes and methods with a set pattern and running them. I've done something kind of similar with remote sensor types (add a function that understands outlet temperature, for instance, and the framework calls it automatically). 456833 of them? That's a lot of typing, though! Commented Apr 18, 2017 at 17:58
  • 1
    @tdelaney There are exceptions to every rule, but in the general case, if you're trying to make and call half a million functions, you're probably doing it wrong. Commented Apr 18, 2017 at 18:00

3 Answers 3

1

You need to store all those distances in a better way.

class NeuralNetwork():
    def __init__(self, inputs, hidden1, hidden2, hidden3, outputs, alpha,it_1,it_2,it_3,it_4,it_5):
        ....
        self.distance1 = [alpha,hidden1,it_1,'train',0,0,0,0,0]
        self.distance2 = [alpha,hidden1,it_1,'test',0,0,0,0,0]
        self.distance3 = [alpha,hidden1,it_1,'dist',0,0,0,0,0]
        ...

I would expect can be compacted, with a list, into:

class NeuralNetwork():
    def __init__(self, inputs, hidden1, hidden2, hidden3, outputs, alpha,it_1,it_2,it_3,it_4,it_5):
        ....
        self.distances = []
        self.distances.append([alpha,hidden1,it_1,'train',0,0,0,0,0])
        self.distances.append([alpha,hidden1,it_1,'test',0,0,0,0,0])
        self.distances.append([alpha,hidden1,it_1,'dist',0,0,0,0,0])
        ...

or better yet:

class NeuralNetwork():
    def __init__(self, inputs, hidden1, hidden2, hidden3, outputs, alpha, *iterations):
        ....
        self.distances = []
        for iteration in interations:
            for type in ['train', 'test', 'dist']:
                self.distances.append([alpha, hidden1, iteration, type, 0, 0, 0, 0, 0])

Presumably, given you have half a million entries, there are other variables involved, but it's the same idea: loop over them into a list.

and then written out as:

def write(self):
    with open('distances.txt', 'a') as file:
        for distance in self.distances:
            file.write('\n'+str(distance))
Sign up to request clarification or add additional context in comments.

4 Comments

I definitly need to learn to see those loops quickly. I am still struggeling. My whole code is filled with trash like this Q.Q
@Perm.Questiin It would probably be worthwhile to go through some loop/list tutorials
I am cleaning up right now and it's going rather well :) went from 600 lines to 200 already :D
@Perm.Questiin Also, it's worth noting those self.distanceXs are attributes, not functions. And in the future, please include a minimal reproducible example with your actual code... it would save all the back and forth :) Goodluck with the refactor.
0

I'm assuming you are iterating from same file, if so...

def a():
    pass

def b():    
    pass

g = globals()

g = g.items()

for i, symbol  in  g:
    if callable(symbol):
        print(i, symbol)

this outputs

('a', <function a at 0x107516c08>)
('b', <function b at 0x1075180c8>)

6 Comments

Note: callable used to be deprecated but not now. So check before using it. bugs.python.org/issue10518
This doesn't call functions with the signature OP requests.
symbol has reference to callable ,you can directly call it like normal function. eg. symbol() //with no arguments symbol(3, 4) // with arguments
No, symbol is just the name of the function. You'd have to do globals()[symbol](). And what if the symbol was launch_the_missles? You still have to check whether it fits the name pattern.
Nope. symbol is callable see output again; It says <function a at 0x107516c08> means it's object of function. I did try locally before commenting. I was able call function with symbol().
|
0

Assuming the loop is in the same module, the functions are in globals()

for i in range(1, 456834):
    globals()["Func{}".format(i)]()

If function numbers aren't consecutive, you could filter the namespace and then call

import re

for fctn in sorted(obj for name,obj in globals().items() if re.match(r'Func\d+$' name)):
    fctn()

2 Comments

...But you probably shouldn't do this.
@Carcigenicate - maybe its crowd-sourced

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.