desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Decide what to do with an "Expect: 100-continue" header. If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before waiting for the request body. The default is to always respond with a 100 Continue. You can behave differently (for example, reject unauthor...
def handle_expect_100(self):
self.send_response_only(100) self.end_headers() return True
'Handle a single HTTP request. You normally don\'t need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.'
def handle_one_request(self):
try: self.raw_requestline = self.rfile.readline(65537) if (len(self.raw_requestline) > 65536): self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) return if (not self.raw_requestline): ...
'Handle multiple requests if necessary.'
def handle(self):
self.close_connection = 1 self.handle_one_request() while (not self.close_connection): self.handle_one_request()
'Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long entry matching the response code. This sends an err...
def send_error(self, code, message=None, explain=None):
try: (shortmsg, longmsg) = self.responses[code] except KeyError: (shortmsg, longmsg) = ('???', '???') if (message is None): message = shortmsg if (explain is None): explain = longmsg self.log_error('code %d, message %s', code, message) content = (self.err...
'Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date.'
def send_response(self, code, message=None):
self.log_request(code) self.send_response_only(code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
'Send the response header only.'
def send_response_only(self, code, message=None):
if (message is None): if (code in self.responses): message = self.responses[code][0] else: message = '' if (self.request_version != 'HTTP/0.9'): if (not hasattr(self, '_headers_buffer')): self._headers_buffer = [] self._headers_buffer.append(('...
'Send a MIME header to the headers buffer.'
def send_header(self, keyword, value):
if (self.request_version != 'HTTP/0.9'): if (not hasattr(self, '_headers_buffer')): self._headers_buffer = [] self._headers_buffer.append(('%s: %s\r\n' % (keyword, value)).encode('latin-1', 'strict')) if (keyword.lower() == 'connection'): if (value.lower() == 'close'): ...
'Send the blank line ending the MIME headers.'
def end_headers(self):
if (self.request_version != 'HTTP/0.9'): self._headers_buffer.append('\r\n') self.flush_headers()
'Log an accepted request. This is called by send_response().'
def log_request(self, code='-', size='-'):
self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
'Log an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). Arguments are the same as for log_message(). XXX This should go to the separate error log.'
def log_error(self, format, *args):
self.log_message(format, *args)
'Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it\'...
def log_message(self, format, *args):
sys.stderr.write(('%s - - [%s] %s\n' % (self.address_string(), self.log_date_time_string(), (format % args))))
'Return the server software version string.'
def version_string(self):
return ((self.server_version + ' ') + self.sys_version)
'Return the current date and time formatted for a message header.'
def date_time_string(self, timestamp=None):
if (timestamp is None): timestamp = time.time() (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(timestamp) s = ('%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)) return s
'Return the current time formatted for logging.'
def log_date_time_string(self):
now = time.time() (year, month, day, hh, mm, ss, x, y, z) = time.localtime(now) s = ('%02d/%3s/%04d %02d:%02d:%02d' % (day, self.monthname[month], year, hh, mm, ss)) return s
'Return the client address.'
def address_string(self):
return self.client_address[0]
'Serve a GET request.'
def do_GET(self):
f = self.send_head() if f: try: self.copyfile(f, self.wfile) finally: f.close()
'Serve a HEAD request.'
def do_HEAD(self):
f = self.send_head() if f: f.close()
'Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing furthe...
def send_head(self):
path = self.translate_path(self.path) f = None if os.path.isdir(path): if (not self.path.endswith('/')): self.send_response(301) self.send_header('Location', (self.path + '/')) self.end_headers() return None for index in ('index.html', 'index.h...
'Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head().'
def list_directory(self, path):
try: list = os.listdir(path) except OSError: self.send_error(404, 'No permission to list directory') return None list.sort(key=(lambda a: a.lower())) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecode...
'Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)'
def translate_path(self, path):
path = path.split('?', 1)[0] path = path.split('#', 1)[0] trailing_slash = path.rstrip().endswith('/') try: path = urllib.parse.unquote(path, errors='surrogatepass') except UnicodeDecodeError: path = urllib.parse.unquote(path) path = posixpath.normpath(path) words = path.spli...
'Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replac...
def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)
'Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file\'s extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (...
def guess_type(self, path):
(base, ext) = posixpath.splitext(path) if (ext in self.extensions_map): return self.extensions_map[ext] ext = ext.lower() if (ext in self.extensions_map): return self.extensions_map[ext] else: return self.extensions_map['']
'Serve a POST request. This is only implemented for CGI scripts.'
def do_POST(self):
if self.is_cgi(): self.run_cgi() else: self.send_error(501, 'Can only POST to CGI scripts')
'Version of send_head that support CGI scripts'
def send_head(self):
if self.is_cgi(): return self.run_cgi() else: return SimpleHTTPRequestHandler.send_head(self)
'Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly. The default ...
def is_cgi(self):
collapsed_path = _url_collapse_path(urllib.parse.unquote(self.path)) dir_sep = collapsed_path.find('/', 1) (head, tail) = (collapsed_path[:dir_sep], collapsed_path[(dir_sep + 1):]) if (head in self.cgi_directories): self.cgi_info = (head, tail) return True return False
'Test whether argument path is an executable file.'
def is_executable(self, path):
return executable(path)
'Test whether argument path is a Python script.'
def is_python(self, path):
(head, tail) = os.path.splitext(path) return (tail.lower() in ('.py', '.pyw'))
'Execute a CGI script.'
def run_cgi(self):
(dir, rest) = self.cgi_info path = ((dir + '/') + rest) i = path.find('/', (len(dir) + 1)) while (i >= 0): nextdir = path[:i] nextrest = path[(i + 1):] scriptdir = self.translate_path(nextdir) if os.path.isdir(scriptdir): (dir, rest) = (nextdir, nextrest) ...
'Return the dict for the current thread. Raises KeyError if none defined.'
def get_dict(self):
thread = current_thread() return self.dicts[id(thread)][1]
'Create a new dict for the current thread, and return it.'
def create_dict(self):
localdict = {} key = self.key thread = current_thread() idt = id(thread) def local_deleted(_, key=key): thread = wrthread() if (thread is not None): del thread.__dict__[key] def thread_deleted(_, idt=idt): local = wrlocal() if (local is not None): ...
'Get optional transport information.'
def get_extra_info(self, name, default=None):
return self._extra.get(name, default)
'Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol\'s connection_lost() method will (eventually) called with None as its argument.'
def close(self):
raise NotImplementedError
'Pause the receiving end. No data will be passed to the protocol\'s data_received() method until resume_reading() is called.'
def pause_reading(self):
raise NotImplementedError
'Resume the receiving end. Data received will once again be passed to the protocol\'s data_received() method.'
def resume_reading(self):
raise NotImplementedError
'Set the high- and low-water limits for write flow control. These two values control when to call the protocol\'s pause_writing() and resume_writing() methods. If specified, the low-water limit must be less than or equal to the high-water limit. Neither value can be negative. The defaults are implementation-specific....
def set_write_buffer_limits(self, high=None, low=None):
raise NotImplementedError
'Return the current size of the write buffer.'
def get_write_buffer_size(self):
raise NotImplementedError
'Write some data bytes to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously.'
def write(self, data):
raise NotImplementedError
'Write a list (or any iterable) of data bytes to the transport. The default implementation concatenates the arguments and calls write() on the result.'
def writelines(self, list_of_data):
if (not _PY34): list_of_data = ((bytes(data) if isinstance(data, memoryview) else data) for data in list_of_data) self.write(''.join(list_of_data))
'Close the write end after flushing buffered data. (This is like typing ^D into a UNIX program reading from stdin.) Data may still be received.'
def write_eof(self):
raise NotImplementedError
'Return True if this transport supports write_eof(), False if not.'
def can_write_eof(self):
raise NotImplementedError
'Close the transport immediately. Buffered data will be lost. No more data will be received. The protocol\'s connection_lost() method will (eventually) be called with None as its argument.'
def abort(self):
raise NotImplementedError
'Send data to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously. addr is target socket address. If addr is None use target address pointed on transport creation.'
def sendto(self, data, addr=None):
raise NotImplementedError
'Close the transport immediately. Buffered data will be lost. No more data will be received. The protocol\'s connection_lost() method will (eventually) be called with None as its argument.'
def abort(self):
raise NotImplementedError
'Get subprocess id.'
def get_pid(self):
raise NotImplementedError
'Get subprocess returncode. See also http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode'
def get_returncode(self):
raise NotImplementedError
'Get transport for pipe with number fd.'
def get_pipe_transport(self, fd):
raise NotImplementedError
'Send signal to subprocess. See also: docs.python.org/3/library/subprocess#subprocess.Popen.send_signal'
def send_signal(self, signal):
raise NotImplementedError
'Stop the subprocess. Alias for close() method. On Posix OSs the method sends SIGTERM to the subprocess. On Windows the Win32 API function TerminateProcess() is called to stop the subprocess. See also: http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate'
def terminate(self):
raise NotImplementedError
'Kill the subprocess. On Posix OSs the function sends SIGKILL to the subprocess. On Windows kill() is an alias for terminate(). See also: http://docs.python.org/3/library/subprocess#subprocess.Popen.kill'
def kill(self):
raise NotImplementedError
'create an empty tower. x is x-position of peg'
def __init__(self, x):
self.x = x
'Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting....
def connect(self, host='', port=0, timeout=(-999), source_address=None):
if (host != ''): self.host = host if (port > 0): self.port = port if (timeout != (-999)): self.timeout = timeout if (source_address is not None): self.source_address = source_address self.sock = socket.create_connection((self.host, self.port), self.timeout, source_add...
'Get the welcome message from the server. (this is read and squirreled away by connect())'
def getwelcome(self):
if self.debugging: print ('*welcome*', self.sanitize(self.welcome)) return self.welcome
'Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF'
def set_debuglevel(self, level):
self.debugging = level
'Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.'
def set_pasv(self, val):
self.passiveserver = val
'Expect a response beginning with \'2\'.'
def voidresp(self):
resp = self.getresp() if (resp[:1] != '2'): raise error_reply(resp) return resp
'Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn\'t seem to work with the servers I\'ve tried. Instead, just send the ABOR command as OOB data.'
def abort(self):
line = ('ABOR' + B_CRLF) if (self.debugging > 1): print ('*put urgent*', self.sanitize(line)) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if (resp[:3] not in {'426', '225', '226'}): raise error_proto(resp) return resp
'Send a command and return the response.'
def sendcmd(self, cmd):
self.putcmd(cmd) return self.getresp()
'Send a command and expect a response beginning with \'2\'.'
def voidcmd(self, cmd):
self.putcmd(cmd) return self.voidresp()
'Send a PORT command with the current host and the given port number.'
def sendport(self, host, port):
hbytes = host.split('.') pbytes = [repr((port // 256)), repr((port % 256))] bytes = (hbytes + pbytes) cmd = ('PORT ' + ','.join(bytes)) return self.voidcmd(cmd)
'Send a EPRT command with the current host and the given port number.'
def sendeprt(self, host, port):
af = 0 if (self.af == socket.AF_INET): af = 1 if (self.af == socket.AF_INET6): af = 2 if (af == 0): raise error_proto('unsupported address family') fields = ['', repr(af), host, repr(port), ''] cmd = ('EPRT ' + '|'.join(fields)) return self.voidcmd(cmd)
'Create a new socket and send a PORT command for it.'
def makeport(self):
err = None sock = None for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): (af, socktype, proto, canonname, sa) = res try: sock = socket.socket(af, socktype, proto) sock.bind(sa) except OSError as _: err = _ ...
'Initiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the...
def ntransfercmd(self, cmd, rest=None):
size = None if self.passiveserver: (host, port) = self.makepasv() conn = socket.create_connection((host, port), self.timeout, source_address=self.source_address) try: if (rest is not None): self.sendcmd(('REST %s' % rest)) resp = self.sendcmd(cm...
'Like ntransfercmd() but returns only the socket.'
def transfercmd(self, cmd, rest=None):
return self.ntransfercmd(cmd, rest)[0]
'Login, default anonymous.'
def login(self, user='', passwd='', acct=''):
if (not user): user = 'anonymous' if (not passwd): passwd = '' if (not acct): acct = '' if ((user == 'anonymous') and (passwd in {'', '-'})): passwd = (passwd + 'anonymous@') resp = self.sendcmd(('USER ' + user)) if (resp[0] == '3'): resp = self.sendcmd...
'Retrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. callback: A single parameter callable to be called on each block of data read. blocksize: The maximum number of bytes to read from the socket at one time. [default: 8192] rest: Passed to transfercmd(). [default: None] Returns: T...
def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
self.voidcmd('TYPE I') with self.transfercmd(cmd, rest) as conn: while 1: data = conn.recv(blocksize) if (not data): break callback(data) if ((_SSLSocket is not None) and isinstance(conn, _SSLSocket)): conn.unwrap() return se...
'Retrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called for each line with the trailing CRLF stripped. [default: print_line()] Returns: The response code.'
def retrlines(self, cmd, callback=None):
if (callback is None): callback = print_line resp = self.sendcmd('TYPE A') with self.transfercmd(cmd) as conn: with conn.makefile('r', encoding=self.encoding) as fp: while 1: line = fp.readline((self.maxline + 1)) if (len(line) > self.maxline): ...
'Store a file in binary mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a read(num_bytes) method. blocksize: The maximum data size to read from fp and send over the connection at once. [default: 8192] callback: An optional single parameter callable that is called on each bl...
def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
self.voidcmd('TYPE I') with self.transfercmd(cmd, rest) as conn: while 1: buf = fp.read(blocksize) if (not buf): break conn.sendall(buf) if callback: callback(buf) if ((_SSLSocket is not None) and isinstance(conn,...
'Store a file in line mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a readline() method. callback: An optional single parameter callable that is called on each line after it is sent. [default: None] Returns: The response code.'
def storlines(self, cmd, fp, callback=None):
self.voidcmd('TYPE A') with self.transfercmd(cmd) as conn: while 1: buf = fp.readline((self.maxline + 1)) if (len(buf) > self.maxline): raise Error(('got more than %d bytes' % self.maxline)) if (not buf): break ...
'Send new account name.'
def acct(self, password):
cmd = ('ACCT ' + password) return self.voidcmd(cmd)
'Return a list of files in a given directory (default the current).'
def nlst(self, *args):
cmd = 'NLST' for arg in args: cmd = (cmd + (' ' + arg)) files = [] self.retrlines(cmd, files.append) return files
'List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)'
def dir(self, *args):
cmd = 'LIST' func = None if (args[(-1):] and (type(args[(-1)]) != type(''))): (args, func) = (args[:(-1)], args[(-1)]) for arg in args: if arg: cmd = (cmd + (' ' + arg)) self.retrlines(cmd, func)
'List a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in ...
def mlsd(self, path='', facts=[]):
if facts: self.sendcmd((('OPTS MLST ' + ';'.join(facts)) + ';')) if path: cmd = ('MLSD %s' % path) else: cmd = 'MLSD' lines = [] self.retrlines(cmd, lines.append) for line in lines: (facts_found, _, name) = line.rstrip(CRLF).partition(' ') entr...
'Rename a file.'
def rename(self, fromname, toname):
resp = self.sendcmd(('RNFR ' + fromname)) if (resp[0] != '3'): raise error_reply(resp) return self.voidcmd(('RNTO ' + toname))
'Delete a file.'
def delete(self, filename):
resp = self.sendcmd(('DELE ' + filename)) if (resp[:3] in {'250', '200'}): return resp else: raise error_reply(resp)
'Change to a directory.'
def cwd(self, dirname):
if (dirname == '..'): try: return self.voidcmd('CDUP') except error_perm as msg: if (msg.args[0][:3] != '500'): raise elif (dirname == ''): dirname = '.' cmd = ('CWD ' + dirname) return self.voidcmd(cmd)
'Retrieve the size of a file.'
def size(self, filename):
resp = self.sendcmd(('SIZE ' + filename)) if (resp[:3] == '213'): s = resp[3:].strip() return int(s)
'Make a directory, return its full pathname.'
def mkd(self, dirname):
resp = self.voidcmd(('MKD ' + dirname)) if (not resp.startswith('257')): return '' return parse257(resp)
'Remove a directory.'
def rmd(self, dirname):
return self.voidcmd(('RMD ' + dirname))
'Return current working directory.'
def pwd(self):
resp = self.voidcmd('PWD') if (not resp.startswith('257')): return '' return parse257(resp)
'Quit, and close the connection.'
def quit(self):
resp = self.voidcmd('QUIT') self.close() return resp
'Close the connection without assuming anything about it.'
def close(self):
if (self.file is not None): self.file.close() if (self.sock is not None): self.sock.close() self.file = self.sock = None
'Return a list of hosts mentioned in the .netrc file.'
def get_hosts(self):
return self.__hosts.keys()
'Returns login information for the named host. The return value is a triple containing userid, password, and the accounting field.'
def get_account(self, host):
host = host.lower() user = passwd = acct = None if (host in self.__hosts): (user, passwd, acct) = self.__hosts[host] user = (user or self.__defuser) passwd = (passwd or self.__defpasswd) acct = (acct or self.__defacct) return (user, passwd, acct)
'Return a list of all defined macro names.'
def get_macros(self):
return self.__macros.keys()
'Return a sequence of lines which define a named macro.'
def get_macro(self, macro):
return self.__macros[macro]
'Constructs a Rational. Takes a string like \'3/2\' or \'1.5\', another Rational instance, a numerator/denominator pair, or a float. Examples >>> Fraction(10, -8) Fraction(-5, 4) >>> Fraction(Fraction(1, 7), 5) Fraction(1, 35) >>> Fraction(Fraction(1, 7), Fraction(2, 3)) Fraction(3, 14) >>> Fraction(\'314\') Fraction(3...
def __new__(cls, numerator=0, denominator=None):
self = super(Fraction, cls).__new__(cls) if (denominator is None): if isinstance(numerator, numbers.Rational): self._numerator = numerator.numerator self._denominator = numerator.denominator return self elif isinstance(numerator, float): value = Fr...
'Converts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10).'
@classmethod def from_float(cls, f):
if isinstance(f, numbers.Integral): return cls(f) elif (not isinstance(f, float)): raise TypeError(('%s.from_float() only takes floats, not %r (%s)' % (cls.__name__, f, type(f).__name__))) if math.isnan(f): raise ValueError(('Cannot convert %r to %s.' % ...
'Converts a finite Decimal instance to a rational number, exactly.'
@classmethod def from_decimal(cls, dec):
from decimal import Decimal if isinstance(dec, numbers.Integral): dec = Decimal(int(dec)) elif (not isinstance(dec, Decimal)): raise TypeError(('%s.from_decimal() only takes Decimals, not %r (%s)' % (cls.__name__, dec, type(dec).__name__))) if dec.is_infinite(): ...
'Closest Fraction to self with denominator at most max_denominator. >>> Fraction(\'3.141592653589793\').limit_denominator(10) Fraction(22, 7) >>> Fraction(\'3.141592653589793\').limit_denominator(100) Fraction(311, 99) >>> Fraction(4321, 8765).limit_denominator(10000) Fraction(4321, 8765)'
def limit_denominator(self, max_denominator=1000000):
if (max_denominator < 1): raise ValueError('max_denominator should be at least 1') if (self._denominator <= max_denominator): return Fraction(self) (p0, q0, p1, q1) = (0, 1, 1, 0) (n, d) = (self._numerator, self._denominator) while True: a = (n // d) q2...
'repr(self)'
def __repr__(self):
return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
'str(self)'
def __str__(self):
if (self._denominator == 1): return str(self._numerator) else: return ('%s/%s' % (self._numerator, self._denominator))
'Generates forward and reverse operators given a purely-rational operator and a function from the operator module. Use this like: __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) In general, we want to implement the arithmetic operations so that mixed-mode operations either call an implementation wh...
def _operator_fallbacks(monomorphic_operator, fallback_operator):
def forward(a, b): if isinstance(b, (int, Fraction)): return monomorphic_operator(a, b) elif isinstance(b, float): return fallback_operator(float(a), b) elif isinstance(b, complex): return fallback_operator(complex(a), b) else: return N...
'a + b'
def _add(a, b):
return Fraction(((a.numerator * b.denominator) + (b.numerator * a.denominator)), (a.denominator * b.denominator))
'a - b'
def _sub(a, b):
return Fraction(((a.numerator * b.denominator) - (b.numerator * a.denominator)), (a.denominator * b.denominator))
'a * b'
def _mul(a, b):
return Fraction((a.numerator * b.numerator), (a.denominator * b.denominator))
'a / b'
def _div(a, b):
return Fraction((a.numerator * b.denominator), (a.denominator * b.numerator))
'a // b'
def __floordiv__(a, b):
return math.floor((a / b))
'a // b'
def __rfloordiv__(b, a):
return math.floor((a / b))
'a % b'
def __mod__(a, b):
div = (a // b) return (a - (b * div))
'a % b'
def __rmod__(b, a):
div = (a // b) return (a - (b * div))