0

I created a class, that accepts an argument, and when the type of this argument is not string, it raises an exception. Well, it raises the exception when I want to create an object of this class and the argument is not string, but it creates the object anyway. Is there any way to prevent object from creation?

class Movie():
    def __init__(self, name):
        if type(name) != str:
            raise Exception("name should be string")
        else:
            self.name = name

movie = Movie(1)

Here I get the exception but if I print(movie), I get the location of the object in the memory. I want to get an error, that this name is not defined. Thanks in Advance.

Arash Heidari
  • 71
  • 1
  • 9
  • 2
    probably you would want to override the __new__ method since that controls the creation of an object - see [this post](https://stackoverflow.com/questions/674304/why-is-init-always-called-after-new) – new-dev-123 Aug 06 '19 at 06:27
  • 2
    Maybe with "del self" before raise – Wonka Aug 06 '19 at 06:28
  • 3
    [Cannot reproduce?](https://tio.run/##VU7LDsIgELzzFWtPkBgvxotJjx79BoLtYjehQLrU2K9HQKNxbjuz84hbmoI/5jw4wwzX8CCU6iygYEQLWpOnpLVkdHYP3sz4USvIQtoiykbDrgdOy0@tWAwxwuU5YEwUvOzqK/AUVjfCDauB/L1TXxM6xv@I2nxotr71CzHXleV6rz0pEUtIko1WOb8A) – ForceBru Aug 06 '19 at 06:30
  • If I run your code then "movie" is not defined – Iain Shelvington Aug 06 '19 at 06:31
  • @Wonka That worked. Thanks – Arash Heidari Aug 06 '19 at 06:34
  • @ForceBru I use jupyter notebook. I can still continue without getting an exit code. Thanks anyway. – Arash Heidari Aug 06 '19 at 06:36
  • 2
    Also it's better to use `isinstance(foo, str)` instead of `type(foo) == str` – Pavel Shishmarev Aug 06 '19 at 06:37
  • @A.Heidary do you have something assigned to "movie" already in your terminal? What happens if you try the above in a fresh terminal? – Iain Shelvington Aug 06 '19 at 06:39
  • @A.Heidary, that shouldn't be possible: run `a=int('hello');print(a)`, for example. You should get a `ValueError` while instantiating the `int` object and you shouldn't be able to access `a` if it wasn't previously defined. – ForceBru Aug 06 '19 at 06:40
  • @IainShelvington I did not. I got something like <__main__.Movie at 0x00000bc2423>. with `del self` before `raise` now I get NameError – Arash Heidari Aug 06 '19 at 06:41
  • @ForceBru It's possible in my notebook. :) I've got this, that's why I post this question. – Arash Heidari Aug 06 '19 at 06:42
  • Normally a factory method would be used. Creating and then destroying the object is not a great solution – Pynchia Aug 06 '19 at 06:50

1 Answers1

2

Solution, del self object before raise

class Movie():
    def __init__(self, name):
        if type(name) != str:
            del self
            raise Exception("name should be string")
        else:
            self.name = name
Wonka
  • 1,548
  • 1
  • 13
  • 20