Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
int infinity
#8
You're doing it wrong. Use Sentinel-Objects instead of numbers.
Example: Your function can return 0, -1, positive Integers and None
If you want to check for this return values, your code is getting complex.

Some example code with socket and sentinels:
import time
import socket
import errno


TIMEOUT = object()
BLOCKED = object()
NOROUTE = object()


def time_connect(ip, port):
    with socket.socket() as sock:
        sock.settimeout(10)
        start = time.time()
        try:
            sock.connect((ip, port))
        except socket.timeout:
            return TIMEOUT
        except ConnectionRefusedError:
            return BLOCKED
        except OSError as e:
            if e.errno == errno.EHOSTUNREACH:
                return NOROUTE
            else:
                # raise the OSError
                # if it's another error than
                # EHOSTUNREACH
                raise
        stop = time.time()
        return stop - start


def caller():
    result = time_connect('127.0.0.1', 66)
    if result is TIMEOUT:
        print('Got a timeout')
    elif result is BLOCKED:
        print('Port is closed')
    elif result is NOROUTE:
        print('No route to ip')
    else:
        print('It took', result, 'to connect to the port')


caller()
https://python-patterns.guide/python/sentinel-object/
https://pythonbytes.fm/episodes/show/124...ooking-for
https://treyhunner.com/2019/03/unique-an...in-python/

PS: This will not work, if you're using multiprocessing. In this case the objects are still there, but they have a different memory address. It's a different object as in the main process for example. If you use threading, this is supported, because of shared memory. To reach the same approach with multiprocessing seems difficult for me. You can't overload the is keyword with magic methods.

Use for float-range np.linspace.
You can't get it faster, it's implemented in c.

Having this kind of god-functions, which can handle all possible cases, are too often overcomplicated and wrong.
You never can handle all possible cases in a logical way. This makes the use of the god-function harder.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
int infinity - by Skaperen - Apr-17-2019, 03:34 AM
RE: int infinity - by Gribouillis - Apr-17-2019, 04:37 PM
RE: int infinity - by Skaperen - Apr-19-2019, 02:31 AM
RE: int infinity - by perfringo - Apr-17-2019, 07:30 PM
RE: int infinity - by Skaperen - Apr-19-2019, 10:41 PM
RE: int infinity - by Gribouillis - Apr-17-2019, 09:47 PM
RE: int infinity - by DeaD_EyE - Apr-18-2019, 07:00 AM
RE: int infinity - by Gribouillis - Apr-19-2019, 04:16 AM
RE: int infinity - by DeaD_EyE - Apr-19-2019, 08:51 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020