Repository: Lightning-AI/pytorch-lightning
File: pytorch_lightning/core/lightning.py (Python)

Code before:
            >>> model = SimpleModel()
            >>> torch.jit.save(model.to_torchscript(), "model.pt")  # doctest: +SKIP
            >>> os.path.isfile("model.pt")  # doctest: +SKIP
            True

        Return:
            This LightningModule as a torchscript, regardless of whether file_path is
            defined or not.
        """

        mode = self.training
        with torch.no_grad():
            scripted_module = torch.jit.script(self.eval(), **kwargs)
        self.train(mode)

        if file_path is not None:
            torch.jit.save(scripted_module, file_path)

        return scripted_module

    @property
    def hparams(self) -> Union[AttributeDict, str]:
        if not hasattr(self, "_hparams"):
            self._hparams = AttributeDict()
        return self._hparams

    @hparams.setter
    def hparams(self, hp: Union[dict, Namespace, Any]):
        hparams_assignment_name = self.__get_hparams_assignment_variable()
        self._hparams_name = hparams_assignment_name
        self._set_hparams(hp)

    def __get_hparams_assignment_variable(self):
        """"""
        """
        looks at the code of the class to figure out what the user named self.hparams
        this only happens when the user explicitly sets self.hparams
        """
        try:
            class_code = inspect.getsource(self.__class__)
            lines = class_code.split("\n")
            for line in lines:
                line = re.sub(r"\s+", "", line, flags=re.UNICODE)
                if ".hparams=" in line:
                    return line.split("=")[1]
        except Exception as e:
            return "hparams"

        return None


Review comment (suggestion):
Here you assume that `example_input_array` is a tensor, but this is not true. 
If forward takes `*args`, `example_input_array` is a tuple, and if forward takes `**kwargs`, `example_input_array` must be a dict. 

Code after:
            ...         super().__init__()
            ...         self.l1 = torch.nn.Linear(in_features=64, out_features=4)
            ...
            ...     def forward(self, x):
            ...         return torch.relu(self.l1(x.view(x.size(0), -1)))
            ...
            >>> model = SimpleModel()
            >>> torch.jit.save(model.to_torchscript(), "model.pt")  # doctest: +SKIP
            >>> os.path.isfile("model.pt")  # doctest: +SKIP
            True

        Return:
            This LightningModule as a torchscript, regardless of whether file_path is
            defined or not.
        """

        mode = self.training
        with torch.no_grad():
            if method == 'script':
                torchscript_module = torch.jit.script(self.eval(), **kwargs)
            elif method == 'trace':
                # if no example inputs are provided, try to see if model has example_input_array set
                if example_inputs is None:
                    example_inputs = self.example_input_array
                # automatically send example inputs to the right device and use trace
                torchscript_module = torch.jit.trace(func=self.eval(), example_inputs=example_inputs.to(self.device),
                                                     **kwargs)
            else:
                raise ValueError(f"The 'method' parameter only supports 'script' or 'trace', but value given was:"
                                 f"{method}")
        self.train(mode)

        if file_path is not None:
            torch.jit.save(torchscript_module, file_path)

        return torchscript_module

    @property
    def hparams(self) -> Union[AttributeDict, str]:
        if not hasattr(self, "_hparams"):
            self._hparams = AttributeDict()
        return self._hparams

    @hparams.setter
    def hparams(self, hp: Union[dict, Namespace, Any]):
        hparams_assignment_name = self.__get_hparams_assignment_variable()
        self._hparams_name = hparams_assignment_name
        self._set_hparams(hp)

    def __get_hparams_assignment_variable(self):
        """"""