0

I try to understand how python works and I need a small explanation.
So I wrote a very short example and I have trouble understanding why it doesn't work. I create a test.py:

def a():
    print('a() try to call non existing b()')
    b()

At this stage, if I write in a python shell

>>> import test
>>> test.a()

It doesn't work and it is normal because b() is unknown.
But when I write these following lines, it still not work.

>>> import test
>>> def b():
...     print('b()')
... 
>>> test.a()

A function in a python module can only call a function in the current module and imported modules ?

thibsc
  • 3,747
  • 2
  • 18
  • 38

3 Answers3

2

You would have to define b() within the same test.py where you defined a().

It would work if you created a new python module (python file) where b() is defined and then imported that module into test.py

from another_module import b # refers to function b

def a():
    print("this function calls b")
    b()

Something like the one above would work. Remember that the module that contains function b() and the test.py module should be in the same directory for it to work.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • I understand, thank you. I thought on an interpreted language it might work, but no :) – thibsc Apr 10 '20 at 02:35
  • No problem, glad it helped! When you can mark it as the final answer for future visitors. Stay safe!! – Rohan Nagavardhan Apr 10 '20 at 02:36
  • Yes, I'm just waiting a little if some other people have other explanation or different way to explain. It could help more people maybe ;) – thibsc Apr 10 '20 at 02:40
2

You could redefine b

How do I redefine functions in Python

import test

def b():      # definition of b
  print('b()')

test.b = b  # function b redefined for test

test.a()   # now this works
DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • It's what I tried to experiment :) So you can write module with functions that call non existing functions and declare the non existing function outside the module by an assignation :) – thibsc Apr 10 '20 at 16:30
  • Yes. It's normally used for overwriting existing functions [as this illustrates](https://stackoverflow.com/questions/10829200/override-module-method-where-from-import-is-used) but no reason why the function needs to exists in the imported module. – DarrylG Apr 10 '20 at 16:44
1

You could achieve the behavior that I think you are describing by passing the function b into a as a parameter.

def a(b):
    print('called a')
    # Use the callable argument
    b()
def x():
    print('x')
a(x)

outputs:

called a
x
thibsc
  • 3,747
  • 2
  • 18
  • 38
ml_dave
  • 23
  • 5