0

so I don't get something and would like some help in figuring this out as I can't seem to find anything of use googling around.

I have the following function in a .py file:

def rng(start, stop):
    if start == stop:
        return random.choice([start, stop])
    elif stop < start:
        return random.randrange(stop, start)
    else:
        return random.randrange(start, stop)

Then in another .py file I go ahead, import it and do a print like so:

from random_generator import rng

print(rng(10, 100))

What I don't understand is why do I get 2 numbers printed instead of one? I've been looking into this but am unable to find an answer. If doing the same thing in the random_generator.py file I get only one number, but if importing the function it outputs 2 numbers..

# Output when doing the print in random_generator:
55

# Output when doing the print via importing the rng function in another .py file:
12
44

Edit: There is no other print function in the random_generator.py file, I have deleted the print function after testing this thing.

David
  • 57
  • 2
  • 8
  • By any chance do you still have a call to a print function in `randon_generator.py`? – buran Sep 23 '20 at 07:17
  • "Output when doing the print in random_generator:" So, you have a `print` in _both_ files, right? – tobias_k Sep 23 '20 at 07:18
  • Hey @buran, no, I do not... That was what I initially thought, but it's not the case here. – David Sep 23 '20 at 07:19
  • it's possible there is artifact `random_generaor.pyc` file that still has that call. Make sure to delete it as well. And it's good to use `if __name__ == '__main__':` block anyway for that kind of things – buran Sep 23 '20 at 07:26
  • I am using the ```if __name__ == "__main__":``` in another file, there is no ```random_generator.pyc``` file. – David Sep 23 '20 at 07:30
  • There is always one if you run the script – buran Sep 23 '20 at 07:32
  • Sorry, bad phrasing there, what I meant to say is I deleted the .pyc file and tried it again, but I am getting the same result. – David Sep 23 '20 at 08:08
  • I have figured it out, is due to one of the imports I'm using, it goes trough the ```__init__.py``` file that gets redirected to the file where I'm using the import and that one gets called first, after the second number displayed is the one I thought was being called two times, but it actually gets called only once. Thus giving me 2 results. Took me a while... – David Sep 23 '20 at 10:15

0 Answers0