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 :)

Community
  • 1
  • 1
Perm. Questiin
  • 401
  • 1
  • 8
  • 19
  • Combine that with https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python?rq=1 – Nick T Apr 18 '17 at 17:07
  • 2
    Is there any reason you have (it seems) 456833 functions rather than a single function with an extra parameter? – John Coleman Apr 18 '17 at 17:10
  • All functions within python code get stored inside of a Foo.__dict__ – Zach Schulze Apr 18 '17 at 17:10
  • 5
    This feels like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. What are you trying to accomplish by doing this? – Chris Apr 18 '17 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? – TemporalWolf Apr 18 '17 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! – tdelaney Apr 18 '17 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. – TemporalWolf Apr 18 '17 at 18:00
  • 1
    @TemporalWolf I updated my post with the reason for asking the question. I have a lot of duplicate code and didn't know how to get rid of it. – Perm. Questiin Apr 18 '17 at 19:11
  • 1
    @Perm.Questiin Where are you getting all the `self.distanceX` attributes from? Can you post that portion? – TemporalWolf Apr 18 '17 at 19:13
  • @TemporalWolf Updated – Perm. Questiin Apr 18 '17 at 19:51

3 Answers3

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))
TemporalWolf
  • 6,474
  • 1
  • 26
  • 42
  • 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 Apr 18 '17 at 20:46
  • 1
    @Perm.Questiin It would probably be worthwhile to go through some loop/list tutorials – TemporalWolf Apr 18 '17 at 20:50
  • 1
    I am cleaning up right now and it's going rather well :) went from 600 lines to 200 already :D – Perm. Questiin Apr 18 '17 at 21:07
  • 1
    @Perm.Questiin Also, it's worth noting those `self.distanceX`s are `attributes`, not `functions`. And in the future, please include a [mcve] with your actual code... it would save all the back and forth :) Goodluck with the refactor. – TemporalWolf Apr 18 '17 at 21:11
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()
tdelaney
  • 55,698
  • 4
  • 59
  • 89
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>)
Harshal Dhumal
  • 841
  • 1
  • 7
  • 15
  • Note: callable used to be deprecated but not now. So check before using it. http://bugs.python.org/issue10518 – Harshal Dhumal Apr 18 '17 at 17:27
  • This doesn't call functions with the signature OP requests. – tdelaney Apr 18 '17 at 17:33
  • 1
    symbol has reference to callable ,you can directly call it like normal function. eg. symbol() //with no arguments symbol(3, 4) // with arguments – Harshal Dhumal Apr 18 '17 at 17:43
  • 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. – tdelaney Apr 18 '17 at 17:53
  • Nope. symbol is callable see output again; It says means it's object of function. I did try locally before commenting. I was able call function with symbol(). – Harshal Dhumal Apr 18 '17 at 18:08
  • oh, yeah, you got `items`. I didn't notice. – tdelaney Apr 18 '17 at 18:17