-1

I have declared function:

def time_between_pulses_checking(self,
                                 channels: list,
                                 max_time_difference: float,
                                 active_pulse_level: int = 0) -> tuple:

When I want to call this function, I pass a list as the channels parameter. This list should contain at least 2 values.

I can check it with the following instruction: if len(channels) >= 2: but I would prefer that when calling the function there was a hint that, for example -> the list passed is too short.

How can I do this?

4
  • That is how. You could move it to e.g. a decorator if you want to deduplicate its use in multiple functions.
    – jonrsharpe
    Feb 8 at 9:56
  • What do you mean by a hint? Do you: 1. Expect the function to fail 2. Print a warning 3. Be colored with a warning in the IDE you're using
    – Hetzroni
    Feb 8 at 9:57
  • When I declare a parameter type in docstrings and when calling a function, I pass a different type as a parameter, I get a warning in pycharm. I would like to achieve something similar by passing a list of too short a length to a function. Feb 8 at 10:04
  • @Jkozdoncher PyCharm can't know what the list will contain when the program runs.
    – Matthias
    Feb 8 at 10:14

1 Answer 1

0

That isn't something supported by the newish Python type hints, but you could break down the channels into two separate arguments:

def time_between_pulses_checking(self,
                                 channel1,
                                 channel2,
                                 max_time_difference: float,
                                 active_pulse_level: int = 0) -> tuple:

If the number of channels is a variant then you could set as such:

def time_between_pulses_checking(self,
                                 *channels,
                                 max_time_difference: float,
                                 active_pulse_level: int = 0):

This way you can call it:

time_between_pulses_checking('ch1', 'ch2', 'ch3', 'chn',
                             max_time_difference=5)

The max_time_difference and active_pulse_level are keyword only arguments here.

You could use this to force at least two channels as:

def time_between_pulses_checking(self,
                                 channel_1,
                                 channel_2,
                                 /,
                                 *etc_channels,
                                 max_time_difference: float,
                                 active_pulse_level: int = 0):
1
  • This solution is ok when I expect only two channels. But 2 channels or more can be passed to the function. Feb 8 at 10:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.