How do you create a function which will return different things depending whether it is called on its own or within another function? My example is that in a function: make_wave_snapshot(size,wavelength,phase), it returns a 2-d array and also diplays a greyscale image. The other function: make_wave_sequence(size,wavelength,nsteps) returns a 3-d array and also a greyscale image that automatically cycles through the greyscale images of each step.
def make_wave_snapshot(size,wavelength,phase):
waves_array = np.zeros((size,size),np.float)
if size%2==0:
for y in range(size):
for x in range(size):
r = math.hypot((size/2 - x - 0.5),(size/2 - y - 0.5))
d = np.sin((2*math.pi*r/wavelength)-phase)/np.sqrt(r)
waves_array[y,x] = d
!!! # dp.display_2d_array(waves_array) #Shows visual representation
return waves_array #Displays array showing values
else:
return 'Please use integer of size.'
def make_wave_sequence(size,wavelength,nsteps):
waves_sequence = np.zeros((nsteps,size,size),np.float)
if nsteps%1==0:
for z in range(nsteps):
waves_sequence[z] = make_wave_snapshot(size,wavelength,(2*math.pi*z/nsteps))
!!! # dp.display_3d_array(waves_sequence)
return waves_sequence #Displays array showing values
else:
return 'Please use positive integer for number of steps'
I know of if name = main and I think it would probably be the answer, but it’s just something I’ve been told is good for checking functions and I don’t have any idea how to fit it into an actual function. Thank you.
You don’t. And it’s not even required for your use case.
This would in theory be possible by using the inspect module or other ways of checking stack frames, but it would be an extremely bad idea. A function should be predictable and do the same thing regardless of where it’s called.
Also note that checking
__name__won’t help you because it contains the module name (or__main__if the script is the entry point) and does not have anything to do with the scope a function is called in.If you want your function to do two different things, one way would be to use an extra argument defaulting to
None, which you use as a flag to indicate if the function should follow the second path:In your case (if I understand it correctly), you don’t want to display the image when calling
make_wave_snapshotinside ofmake_wave_sequence. This has nothing to do with return values and can be solved by using adding an extra argument to the function as described above:And now you simply call it with an extra
Falseinside of the other function:Oh, and please never use return values as an indication of error conditions as you’re doing in the
elsecase of your loops. You’re not writing C here, python is a civilized language that has Exceptions – use them.