I have a class called EasyUrl()
that is derived from urlparse.Parseresult()
. ParseResult()
is instantiated when calling urlparse.urlparse(url)
, I have a static method inside EasyUrl()
that changes the class type of the instantiated ParseResult()
object into a EasyUrl()
object. I wrap the urlparse.urlparse()
function and the class type conversion into a function parse_url()
.
The reason behind such a function, is my attempt to hack around a separate problem I don't require an answer to but would like one, is I get a TypeError
when __new__
is called during the instantiating process, which lets me know I have an invalid number of arguments.
Error received when instantiating EasyUrl()
directly
# snippet
url = 'stackoverflow.com'
url = EasyUrl(url)
# snippet end
Output:
TypeError: __new__() takes exactly 7 arguments (2 given)
The ParseResult()
class inherits from a namedtuple()
.
Excerpt from urlparse library
class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin):
__slots__ = ()
def geturl(self):
return urlunparse(self)
Now that I have described a little functionality of the code, here is the problem. I can't access the named tuple's (ParseResult) attributes. I'm trying to implement a default scheme for ParseResult()
if it is missing.
But I can't access the attributes in the class definition.
import urlparse
def parse_url(url):
""" Return a parsed EasyUrl() object"""
parse_result = urlparse.urlparse(url)
return EasyUrl.EvolveParseResult(parse_result)
class EasyUrl(urlparse.ParseResult):
@staticmethod
def EvolveParseResult(parse_result):
""" Change the type of class into a EasyUrl() Object."""
parse_result.__class__ = EasyUrl
easy_url = parse_result # For readabilty
easy_url.init()
return easy_url
def __init__(self, url):
self = parse_url(url) # doesn't work
def init(self):
self.url = self.geturl()
#self.set_scheme_if_non() # Uncomment when no error is raised
def set_scheme_if_non(self, scheme='http'):
if not self.scheme:
self.scheme = scheme
self.url = self.geturl() # Rebuild our url with the new scheme
# Passes the set_scheme_if_non trigger
#url = 'https://stackoverflow.com'
# Fails if statment, then attempts to set the variable,
# but error is raised: AttributeError: can't set attribute
url = 'stackoverflow.com'
# Will give the error: TypeError: __new__() takes exactly 7 arguments (2 given)
#url = EasyUrl(url)
# works fine, I don't know why. Except that I can't access
# the tuples attributes in the class definition
url = parse_url(url)
print url.scheme # Works fine
url.set_scheme_if_non() # Raises an error
Output
File "/home/crispycret/easyurl.py", line 50, in <module>
url.set_scheme_if_non() # Raises an error
File "/home/crispycret/easyurl.py", line 29, in set_scheme_if_non
self.scheme = scheme
AttributeError: can't set attribute