ABC for String?

2024/9/19 9:48:11

I recently discovered abstract base classes (ABCs) in collections and like their clear, systematic approach and Mixins. Now I also want to create customs strings (*), but I couldn't find an ABC for strings.

There is UserString, but UserDict was discouraged!? Deriving from str itself would have no Mixins? How would you access the "data" part of the string in overridden methods?

Somewhere I saw the suggestions to derive from Sequence and Hashable, but then I couldn't write if 'test' in my_string:?!

Which approach do you recommend?

(*) The reasons are: - write strings that order in an internally defined way - make string (as part of an enumeration), that throw errors when comparing to values outside the enumeration scope

Answer

Here's a silly, but quick, example of Steven's answer. It's implemented in Python 3 (i.e. Unicode strings, super without arguments, and __getitem__ slices):

class MultiStr(str):def __new__(cls, string, multiplier=1, **kwds):self = super().__new__(cls, string, **kwds)self.multiplier = multiplierreturn selfdef __getitem__(self, index):item = super().__getitem__(index)return item * self.multiplier>>> s = MultiStr(b'spam', multiplier=3, encoding='ascii')
>>> s[0]
'sss'
>>> s[:2]
'spspsp'
>>> s[:]
'spamspamspam'
https://en.xdnf.cn/q/72755.html

Related Q&A

Get the most relevant word (spell check) from enchant suggest() in Python

I want to get the most relevant word from enchant suggest(). Is there any better way to do that. I feel my function is not efficient when it comes to checking large set of words in the range of 100k or…

How do I get python-markdown to additionally urlify links when formatting plain text?

Markdown is a great tool for formatting plain text into pretty html, but it doesnt turn plain-text links into URLs automatically. Like this one:http://www.google.com/How do I get markdown to add tags …

Best way to read aws credentials file

In my python code I need to extract AWS credentials AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID which are stored in the plain text file as described here: https://docs.aws.amazon.com/sdkref/latest/guid…

Profiling on live Django server?

Ive never done code coverage in Python, but Im looking for something like GCCs gcov, which tells me how many times each line executes, or Apples Shark which gives a hierarchial breakdown of how long ea…

Inset axes anchored to specific points in data coordinates?

Id like to be able to overlay multiple inset axes on top of a set of parent axes, something like this:Ideally, Id like the anchor point of each set of inset axes to be fixed in data coordinates, but fo…

No module named folium.plugins, Python 3.6

I am trying to import folium into a Jupyter notebook Im working on and I cannot seem to solve the import issues with the Folium library. Has anyone else solved this problem?After encountering an error…

How you enable CBC to return best solution when timelimit? (Pyomo)

I am trying to use CBC(v2.10.3) on Pyomo to solve for a integer linear problem.When executing the solver, I am currently setting a timelimit of 600s.opt = SolverFactory ("cbc")opt.options[sec…

SSL cert issue with Python Requests

Im making a request to a site which requires SSL cert to access. When I tried to access the URL, I get SSL Certificate errorimport requests proxies = {"https":"https://user:pwd@host:port…

MatplotLib get all annotation by axes

im doing a project with Python and Tkinter. I can plot an array of data and i also implemented a function to add annotation on plot when i click with the mouse, but now i need a list of all annotation…

Using Pandas to applymap with access to index/column?

Whats the most effective way to solve the following pandas problem? Heres a simplified example with some data in a data frame: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randin…