Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get rid of imp / load_source() #1424

Merged
merged 6 commits into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions music21/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,8 @@ def testSortOrder(self):
def testFreezeThaw(self):
from music21 import converter
from music21 import stream
# pylint: disable=redefined-outer-name
from music21.bar import Barline # avoid not same class error

b = Barline()
self.assertNotIn('StyleMixin', b.classes)
Expand Down
2 changes: 0 additions & 2 deletions music21/instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -2424,7 +2424,6 @@ def fromString(instrumentString: str,
>>> t12
<music21.instrument.Clarinet 'Klarinette'>


This case works because the name 'Klarinette' is a recognised instrument name in German
and appears in the German language list.
If you search for a German name like 'Klarinette' on the French list (language='french'),
Expand All @@ -2434,7 +2433,6 @@ def fromString(instrumentString: str,
'english', 'french', 'german', 'italian', 'russian', 'spanish', and 'abbreviation'.

Note that the language string is not case-sensitive, so 'French' is also fine.

'''
from music21.languageExcerpts import instrumentLookup

Expand Down
34 changes: 22 additions & 12 deletions music21/test/commonTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
Things that are common to testing...
'''
import importlib
import importlib.util
from unittest.signals import registerResult

import doctest
Expand All @@ -25,15 +26,25 @@
from music21 import environment
from music21 import common

# import importlib
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
warnings.simplefilter('ignore', PendingDeprecationWarning)
import imp # pylint: disable=deprecated-module
environLocal = environment.Environment('test.commonTest')


environLocal = environment.Environment('test.commonTest')
def load_source(name: str, path: str) -> types.ModuleType:
'''
Replacement for deprecated imp.load_source()

Thanks to:
https://github.com/epfl-scitas/spack for pointing out the
important missing "spec.loader.exec_module(module)" line.
'''
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise FileNotFoundError(f'No such file or directory: {path!r}')
module = importlib.util.module_from_spec(spec)
if module is None:
raise FileNotFoundError(f'No such file or directory: {path!r}')
spec.loader.exec_module(module)
return module

# noinspection PyPackageRequirements
def testImports():
Expand Down Expand Up @@ -207,8 +218,8 @@ def __init__(self, useExtended=False, autoWalk=True):
'abcFormat/testFiles.py',
]
# run these first...
self.slowModules = ['metadata/caching',
'metadata/bundles',
self.slowModules = ['metadata/bundles',
'metadata/caching',
'features',
'graph',
'graph/plot',
Expand All @@ -229,6 +240,7 @@ def __init__(self, useExtended=False, autoWalk=True):

'romanText/translate',
'corpus/testCorpus',
'corpus/corpora',
'audioSearch/transcriber',
'audioSearch/__init__',
'alpha/theoryAnalysis/theoryAnalyzer',
Expand Down Expand Up @@ -367,17 +379,15 @@ def getModule(self, fp, restoreEnvironmentDefaults=False):
if skip:
return None

name = self._getName(fp)
# for importlib
# name = self._getNamePeriod(fp, addM21=True)
name = self._getNamePeriod(fp, addM21=True)

# print(name, os.path.dirname(fp))
try:
with warnings.catch_warnings():
# warnings.simplefilter('ignore', RuntimeWarning)
# importlib is messing with coverage...
mod = imp.load_source(name, fp)
# mod = importlib.import_module(name)
mod = load_source(name, fp)
except Exception as excp: # pylint: disable=broad-except
environLocal.warn(['failed import:', fp, '\n',
'\tEXCEPTION:', str(excp).strip()])
Expand Down
3 changes: 1 addition & 2 deletions music21/test/multiprocessTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def runOneModuleWithoutImp(args):
return ModuleResponse(returnCode='NotInTree', fp=fp, success=success)

try:
moduleName = modGath._getName(fp)
moduleName = modGath._getNamePeriod(fp, addM21=False)

s1 = commonTest.defaultDoctestSuite()

Expand Down Expand Up @@ -174,7 +174,6 @@ def mainPoolRunner(testGroup=('test',), restoreEnvironmentDefaults=False, leaveO
if newResult.moduleName is not None:
mn = newResult.moduleName
mn = mn.replace('___init__', '')
mn = mn.replace('_', '.')
else:
mn = ''
rt = newResult.runTime
Expand Down
1 change: 1 addition & 0 deletions music21/test/test_pitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def testCopyAndDeepcopy(self):
for skip in ['_', '__', 'Test', 'Exception']:
if part.startswith(skip) or part.endswith(skip):
match = True
break
if match:
continue
name = getattr(sys.modules[self.__module__], part)
Expand Down