Skip to content

Commit

Permalink
Remove previously deprecated objects
Browse files Browse the repository at this point in the history
This completely removes all objects which were deprecated in version 3.0 (this change will be included in version 3.4). Given the time that has passed, and the fact that older unmaintained extensions are not likely to support the new minimum Python version, this is little concern about breaking older extensions.
  • Loading branch information
waylan authored May 27, 2022
1 parent dc434df commit a767b2d
Show file tree
Hide file tree
Showing 10 changed files with 36 additions and 292 deletions.
28 changes: 28 additions & 0 deletions docs/change_log/release-3.4.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,34 @@ markdown.markdown(src, extensions=[TableExtension(use_align_attribute=True)])

In addition, tests were moved to the modern test environment.

### Previously deprecated objects have been removed

Various objects were deprecated in version 3.0 and began raising deprecation
warnings (see the [version 3.0 release notes] for details). Any of those object
which remained in version 3.3 have been removed from the codebase in version 3.4
and will now raise errors. A summary of the objects are provided below.

[version 3.0 release notes]: release-3.0.md

| Deprecated Object | Replacement Object |
|----------------------------------------|-------------------------------------|
| `markdown.version` | `markdown.__version__` |
| `markdown.version_info` | `markdown.__version_info__` |
| `markdown.util.etree` | `xml.etree.ElementTree` |
| `markdown.util.string_type` | `str` |
| `markdown.util.text_type` | `str` |
| `markdown.util.int2str` | `chr` |
| `markdown.util.iterrange` | `range` |
| `markdown.util.isBlockLevel` | `markdown.Markdown.is_block_level` |
| `markdown.util.Processor().markdown` | `markdown.util.Processor().md` |
| `markdown.util.Registry().__setitem__` | `markdown.util.Registry().register` |
| `markdown.util.Registry().__delitem__` |`markdown.util.Registry().deregister`|
| `markdown.util.Registry().add` | `markdown.util.Registry().register` |

In addition, the `md_globals` parameter of
`Markdown.extensions.Extension.extendMarkdown()` is no longer recognized as a
valid parameter and will raise an error if provided.

## New features

The following new features have been included in the 3.4 release:
Expand Down
31 changes: 2 additions & 29 deletions markdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,37 +19,10 @@
License: BSD (see LICENSE.md for details).
"""

import sys

# TODO: Remove this check at some point in the future.
# (also remove flake8's 'ignore E402' comments below)
if sys.version_info[0] < 3: # pragma: no cover
raise ImportError('A recent version of Python 3 is required.')

from .core import Markdown, markdown, markdownFromFile # noqa: E402
from .__meta__ import __version__, __version_info__ # noqa: E402
import warnings # noqa: E402
from .core import Markdown, markdown, markdownFromFile
from .__meta__ import __version__, __version_info__ # noqa

# For backward compatibility as some extensions expect it...
from .extensions import Extension # noqa

__all__ = ['Markdown', 'markdown', 'markdownFromFile']

__deprecated__ = {
"version": ("__version__", __version__),
"version_info": ("__version_info__", __version_info__)
}


def __getattr__(name):
"""Get attribute."""

deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if (3, 7) <= sys.version_info else 4)
)
return deprecated[1]
raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))
6 changes: 0 additions & 6 deletions markdown/blockparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,6 @@ def __init__(self, md):
self.state = State()
self.md = md

@property
@util.deprecated("Use 'md' instead.")
def markdown(self):
# TODO: remove this later
return self.md

def parseDocument(self, lines):
""" Parse a markdown document into an ElementTree.
Expand Down
2 changes: 1 addition & 1 deletion markdown/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def registerExtensions(self, extensions, configs):
if isinstance(ext, str):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
ext._extendMarkdown(self)
ext.extendMarkdown(self)
logger.debug(
'Successfully loaded extension "%s.%s".'
% (ext.__class__.__module__, ext.__class__.__name__)
Expand Down
21 changes: 0 additions & 21 deletions markdown/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
License: BSD (see LICENSE.md for details).
"""

import warnings
from ..util import parseBoolValue


Expand Down Expand Up @@ -70,24 +69,6 @@ def setConfigs(self, items):
for key, value in items:
self.setConfig(key, value)

def _extendMarkdown(self, *args):
""" Private wrapper around extendMarkdown. """
md = args[0]
try:
self.extendMarkdown(md)
except TypeError as e:
if "missing 1 required positional argument" in str(e):
# Must be a 2.x extension. Pass in a dumby md_globals.
self.extendMarkdown(md, {})
warnings.warn(
"The 'md_globals' parameter of '{}.{}.extendMarkdown' is "
"deprecated.".format(self.__class__.__module__, self.__class__.__name__),
category=DeprecationWarning,
stacklevel=2
)
else:
raise

def extendMarkdown(self, md):
"""
Add the various processors and patterns to the Markdown Instance.
Expand All @@ -98,8 +79,6 @@ def extendMarkdown(self, md):
* md: The Markdown instance.
* md_globals: Global variables in the markdown module namespace.
"""
raise NotImplementedError(
'Extension "%s.%s" must define an "extendMarkdown"'
Expand Down
8 changes: 1 addition & 7 deletions markdown/extensions/smarty.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
from . import Extension
from ..inlinepatterns import HtmlInlineProcessor, HTML_RE
from ..treeprocessors import InlineProcessor
from ..util import Registry, deprecated
from ..util import Registry


# Constants for quote education.
Expand Down Expand Up @@ -155,12 +155,6 @@ def __init__(self, pattern, replace, md):
self.replace = replace
self.md = md

@property
@deprecated("Use 'md' instead.")
def markdown(self):
# TODO: remove this later
return self.md

def handleMatch(self, m, data):
result = ''
for part in self.replace:
Expand Down
6 changes: 0 additions & 6 deletions markdown/inlinepatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,6 @@ def __init__(self, pattern, md=None):

self.md = md

@property
@util.deprecated("Use 'md' instead.")
def markdown(self):
# TODO: remove this later
return self.md

def getCompiledRegExp(self):
""" Return a compiled regular expression. """
return self.compiled_re
Expand Down
6 changes: 0 additions & 6 deletions markdown/treeprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,6 @@ def __init__(self, md):
self.inlinePatterns = md.inlinePatterns
self.ancestors = []

@property
@util.deprecated("Use 'md' instead.")
def markdown(self):
# TODO: remove this later
return self.md

def __makePlaceholder(self, type):
""" Generate a placeholder """
id = "%04d" % len(self.stashed_nodes)
Expand Down
106 changes: 0 additions & 106 deletions markdown/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,11 @@
import re
import sys
import warnings
import xml.etree.ElementTree
from collections import namedtuple
from functools import wraps, lru_cache
from itertools import count


# TODO: Remove deprecated variables in a future release.
__deprecated__ = {
'etree': ('xml.etree.ElementTree', xml.etree.ElementTree),
'string_type': ('str', str),
'text_type': ('str', str),
'int2str': ('chr', chr),
'iterrange': ('range', range)
}


"""
Constants you might want to modify
-----------------------------------------------------------------------------
Expand Down Expand Up @@ -121,15 +110,6 @@ def deprecated_func(*args, **kwargs):
return wrapper


@deprecated("Use 'Markdown.is_block_level' instead.")
def isBlockLevel(tag):
"""Check if the tag is a block level HTML tag."""
if isinstance(tag, str):
return tag.lower().rstrip('/') in BLOCK_LEVEL_ELEMENTS
# Some ElementTree tags are not strings, so return False.
return False


def parseBoolValue(value, fail_on_errors=True, preserve_none=False):
"""Parses a string representing bool value. If parsing was successful,
returns True or False. If preserve_none=True, returns True, False,
Expand Down Expand Up @@ -191,12 +171,6 @@ class Processor:
def __init__(self, md=None):
self.md = md

@property
@deprecated("Use 'md' instead.")
def markdown(self):
# TODO: remove this later
return self.md


class HtmlStash:
"""
Expand Down Expand Up @@ -382,83 +356,3 @@ def _sort(self):
if not self._is_sorted:
self._priority.sort(key=lambda item: item.priority, reverse=True)
self._is_sorted = True

# Deprecated Methods which provide a smooth transition from OrderedDict

@deprecated('Use the `register` method instead.')
def __setitem__(self, key, value):
""" Register item with priority 5 less than lowest existing priority. """
if isinstance(key, str):
if key in self:
# Key already exists, replace without altering priority
self._data[key] = value
return
if len(self) == 0:
# This is the first item. Set priority to 50.
priority = 50
else:
self._sort()
priority = self._priority[-1].priority - 5
self.register(value, key, priority)
else:
raise TypeError

@deprecated('Use the `deregister` method instead.')
def __delitem__(self, key):
""" Deregister an item by name. """
if key in self:
self.deregister(key)
else:
raise KeyError('Cannot delete key {}, not registered.'.format(key))

@deprecated('Use the `register` method instead.')
def add(self, key, value, location):
""" Register a key by location. """
if len(self) == 0:
# This is the first item. Set priority to 50.
priority = 50
elif location == '_begin':
self._sort()
# Set priority 5 greater than highest existing priority
priority = self._priority[0].priority + 5
elif location == '_end':
self._sort()
# Set priority 5 less than lowest existing priority
priority = self._priority[-1].priority - 5
elif location.startswith('<') or location.startswith('>'):
# Set priority halfway between existing priorities.
i = self.get_index_for_name(location[1:])
if location.startswith('<'):
after = self._priority[i].priority
if i > 0:
before = self._priority[i-1].priority
else:
# Location is first item`
before = after + 10
else:
# location.startswith('>')
before = self._priority[i].priority
if i < len(self) - 1:
after = self._priority[i+1].priority
else:
# location is last item
after = before - 10
priority = before - ((before - after) / 2)
else:
raise ValueError('Not a valid location: "%s". Location key '
'must start with a ">" or "<".' % location)
self.register(value, key, priority)


def __getattr__(name):
"""Get attribute."""

deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if (3, 7) <= sys.version_info else 4)
)
return deprecated[1]
raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))
Loading

0 comments on commit a767b2d

Please sign in to comment.