Home > Enterprise >  Python: What's best practice for variable initialization value that won't render True or F
Python: What's best practice for variable initialization value that won't render True or F

Time:08-03

I often times find myself initializing an attribute in a class to False, But what I really want is for this to represent True or False ONLY after it is actually assigned to reduce bugs in the future. For instance, the attribute isDog I want to assign later in the methods to either True or False, but I hate having to assign the default to "False" since it leaves room for bugs in the future and seems to assume a priori it's not a dog. Is there a best practice or standard for what I could assign this to that won't render in boolean logic (instead, printing an error if used in Boolean logic) so that I don't need to preassign as False?

CodePudding user response:

A good option is to define your variable as None and check if it is defined before using it.

Here an example:

class Animal:
    def __init__(self):
        self.is_dog: Optional[bool] = None
        ...

    def become_a_dog(self) -> None:
        self.is_dog = True

    def become_a_cat(self) -> None:
        self.is_dog = False

    def can_bark(self) -> bool:
        if self.is_dog is None:
            raise Exception("Animal instance is not yet specified as dog or cat.")
        return self.is_dog

CodePudding user response:

I won't say that this is best practice or standard, however you could use the None keyword to achieve this functionality.

Take a look at the code example below

class Pet:
  def __init__(self):
    self.isDog = None
    self.isCat = None

myCat = Pet()
myCat.isCat = True

if myCat.isDog:
  print('I have a dog!')

if myCat.isCat:
  print('I have a cat!')

if myCat.isDog == None:
  print("I haven't decided whether it's a dog yet")

This code will output "I have a cat!", and "I haven't decided whether it's a dog yet"

CodePudding user response:

Here's a workaround using @property

class Foo:
    def __init__(self):
        self._is_foo = None
        
    @property
    def is_foo(self):
        assert isinstance(self._is_foo, bool), "ERROR!!!"
        return self._is_foo
        
    def set_foo(self, val):
        self._is_foo = val
        
x = Foo()
x.is_foo
# AssertionError: ERROR!!!

x.set_foo(True)
x.is_foo
# True
  • Related