Home > Software engineering >  What are these special class init imput elements in this source code?
What are these special class init imput elements in this source code?

Time:08-05

My situation:

Below the documentation of the a module in the manim library (found here) there have been some __init__ arguments which confused me and I have not been able to reproduce them with a testing class.

A code snippet from the library:

def __init__(
        self,
        x_range: Sequence[float] | None = None,  # must be first
        length: float | None = None,
        ...
        line_to_number_buff: float = MED_SMALL_BUFF,
        decimal_number_config: dict | None = None,
        numbers_to_exclude: Iterable[float] | None = None,
        **kwargs,
    ):
...

Question: Now I am wondering about multiple statements there. How can I understand the following code elements:

  1. x_range: Sequence[float] | None = None
  2. length: float | None = None
  3. line_to_number_buff: float = MED_SMALL_BUFF
  4. decimal_number_config: dict | None = None
  5. numbers_to_exclude: Iterable[float] | None = None

Precise questions:

  1. What happens if e.g. x_range is no Sequence and what happens if the Sequence is not of type float?
  2. What happens for point 3 above if no entry of type float if passed into the argument? Is the MED_SMALL_BUFF a value if no specific value is specified?

My assumptions:

  1. The colons specify the type of the element which are passed into the __init__ dunder-method for the arguments.
  2. The | is an logical or which sets the value before the colos equal to None. Nontheless I don't understand which None is set to None by None = None.

CodePudding user response:

The values after = are the default values for the parameters. For instance, if you don't pass the line_to_number_buff argument, it defaults to MED_SMALL_BUF.

Where it has sometype | None, it means you can pass either a value of sometype or you can pass None. You're not generally expected to pass None explicitly (but you can); these parameters default to None, and the type hint allows for this.

If you don't pass a value of the type specified, you'll probably get an error. The function might check the type explicitly and report a TypeError itself, but more likely it just uses the value when calling some other code that expects that type. The bad value could propagate through numerous functions before it gets to something that actually checks, and that will report the error.

  • Related