user9013730
user9013730

Reputation:

Data Type `NoneType` comparison?

I'm trying to validate the port number (range 1-65535) inside URL using urlparse.

The tricky part is if the URL doesn't have port number in it, urlparse(url).port is identified as NoneType

Hence, I tried to make a simple comparison based on the data type, but didn't really work as you can see in this example.

If I use NoneType as a data type,

elif type(u.port) == NoneType:

I'm getting error

NameError: name 'NoneType' is not defined

I did not use validators as it can't validate the port number correctly.

Python: `validators.url` does not accept port number from 1-9, but accept port bigger than 65535?

TCP/UDP port number range is started from 1-65535. However, validators unable to recognize port 1-9 and still accepting invalid port bigger than 65535.

Code

from urllib.parse import urlparse

def test(url):
    global u
    u = urlparse(url)
    print(' Port      : ', u.port)
    print(' Data Type : u.port %s\n'% type(u.port))

for url in ['example.com', 'example.com:1', 'http://example.com:1']:
    print(url)
    test(url)
    if type(u.port) == int:
        print(' Integer')
    elif type(u.port) == None:
        print(' None')
    # elif type(u.port) == NoneType:        # NameError: name 'NoneType' is not defined
    #   print(' None')

Output

example.com
 Port      :  None
 Data Type : u.port <class 'NoneType'>

example.com:1
 Port      :  None
 Data Type : u.port <class 'NoneType'>

http://example.com:1
 Port      :  1
 Data Type : u.port <class 'int'>

    Integer

Upvotes: 0

Views: 390

Answers (2)

Chiheb.K
Chiheb.K

Reputation: 156

You can also check the NoneType by:

elif isinstance(u.port, type(None)):
    print(' None')

Upvotes: 1

James
James

Reputation: 36691

Don't compare types to check for None, use:

elif u.port is None:
    print(' None')

Upvotes: 6

Related Questions