python class: there a bewtter way to write this property/attribute ?


import time, random



class MyObject:
    def __init__(self):
        self.timeout = 0.0
    
    @property
    def timeout(self):
        return False if time.clock() < self.__timeout else True
    
    @timeout.setter
    def timeout(self, args):
        try:    start, end  = args
        except: start = end = args
        self.__timeout = time.clock() + random.uniform(start, end)


myob.timeout = 10 # timeout set to 10 seconds
myob.timeout = 10, 15 # timeout set in a range 10-15 seconds

i mean the try/except
the problem is that i not know the number of element, can be one or two …
tried something with *args , but not work

some idea?

if you use *args

“args” will be a list starting with the first argument.

See Python docs

tryed using *args, but not work:


import time, random






class MyObject:
    def __init__(self):
        self.timeout = 0.0
    @property
    def timeout(self):
        return False if time.clock() < self.__timeout else True
    @timeout.setter
    def timeout(self, *args):
        if len(args)>1:
            start, end = args
        else :
            start = end = args[0]
        self.__timeout = time.clock() + random.uniform(start, end)
        
        
        
        
myob=MyObject()
myob.timeout = 1,2



You know that setters deal with one argument only?

In your example it the Arbitrary Argument Lists is not sufficient. They are strong when you enter an unknown number of objects that should be dealt equally. Such as print(“a”,1,id(x)).

In your example each argument has a specific purpose (start, end). So you better use the normal argument notation generateRandomTime(start, end). You can skip the later arguments by assigning a default value: generateRandomTime(start, end=None)

If you still want to use several object together with the property syntax, you can place them into a container:


myObject.timeout = [1,2]

“You know that setters deal with one argument only?”

not was so clear

so , the try/except is necessary (or function() explicit) , ok thanks :wink:

Better do not use except without an explicit error. Otherwise it will catch any error. So you will never see that they occurred.

The only reason to catch all errors is, when you want to deal with all of them e.g. by encapsulating code very strong. You still should deal with them rather than silently ignore them.

An house will still burn even without a smoke detector. The only difference … there is less chance you can rescue yourself if it happens. The same belongs to code. Accept that there are errors, deal with them. It could even mean to forward the error to someone else.