prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def <|fim_middle|>(self, destination):
self.destination = destination
def send_alert(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def __init__(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def switch_status(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def send_alert(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def monitor_switch(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | __init__ |
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def __init__(self, destination):
self.destination = destination
def <|fim_middle|>(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def __init__(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def switch_status(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def send_alert(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def monitor_switch(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | send_alert |
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def __init__(self, destination):
self.destination = destination
def send_alert(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def <|fim_middle|>(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def switch_status(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def send_alert(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def monitor_switch(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | __init__ |
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def __init__(self, destination):
self.destination = destination
def send_alert(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def __init__(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def <|fim_middle|>(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def send_alert(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def monitor_switch(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | switch_status |
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def __init__(self, destination):
self.destination = destination
def send_alert(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def __init__(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def switch_status(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def <|fim_middle|>(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def monitor_switch(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | send_alert |
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
import time
import sys
import sarcli
import idigidata
def millisecond_timestamp():
"""
Return a timestamp, in milliseconds
:return ms_timestamp: int, Timestamp in milliseconds
"""
ms_timestamp = int(time.time() * 1000)
return ms_timestamp
def cli_command(cmd):
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(object):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:return response: str, Response to sendsms command
"""
message = "{0}: {1}".format(self.custom_text, message)
command = 'sendsms ' + self.destination + ' "' + message + '" '
response = cli_command(command)
return response
class DatapointAlert(object):
"""
Send a Datapoint alert
"""
def __init__(self, destination):
self.destination = destination
def send_alert(self, message):
"""
Send a Datapoint alert
:param message: str, Datapoint content
:return response: tuple, Result code of datapoint upload attempt
"""
timestamp = millisecond_timestamp()
dpoint = """\
<DataPoint>
<dataType>STRING</dataType>
<data>{0}</data>
<timestamp>{1}</timestamp>
<streamId>{2}</streamId>
</DataPoint>""".format(message, timestamp, self.destination)
response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml")
return response
class DoorMonitor(object):
"""
Provides methods to monitor the enclosure door status
"""
def __init__(self, alert_list):
self.d1_status = ""
self.alert_list = alert_list
@classmethod
def switch_status(cls):
"""
Reads line status and sends an alert if the status is different
:return status: str, Door status, "OPEN" or "CLOSED"
"""
response = cli_command("gpio dio")
if "D1: DOUT=OFF, DIN=LOW" in response:
if not "D0: DOUT=ON" in response:
# Door is closed
status = "CLOSED"
else:
# Door is open
status = "OPEN"
return status
def send_alert(self, text):
"""
:param text: str, Alert content
:return:
"""
for alert in self.alert_list:
alert.send_alert(text)
def <|fim_middle|>(self):
"""
Runs line monitoring and alerting in a loop
:return:
"""
while True:
status = self.switch_status()
if status != self.d1_status:
print "WR31 door is: {0}".format(status)
self.send_alert(status)
self.d1_status = status
time.sleep(.5)
if __name__ == '__main__':
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")]
if len(sys.argv) >= 3:
CUSTOM_TEXT = sys.argv[2]
else:
CUSTOM_TEXT = "WR31 Door"
if len(sys.argv) >= 2:
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
MONITOR = DoorMonitor(ALERT_FUNCTIONS)
MONITOR.monitor_switch()
<|fim▁end|> | monitor_switch |
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for tumuli project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os<|fim▁hole|>from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tumuli.settings")
application = get_wsgi_application()<|fim▁end|> | |
<|file_name|>TestTemporalColorTracker.py<|end_file_name|><|fim▁begin|>from SimpleCV import Camera, Image, Color, TemporalColorTracker, ROI, Display
import matplotlib.pyplot as plt
cam = Camera(1)
tct = TemporalColorTracker()
img = cam.getImage()
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
tct.train(cam,roi=roi,maxFrames=250,pkWndw=20)
# Matplot Lib example plotting
plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'}
for key in tct.data.keys():
plt.plot(tct.data[key],plotc[key])
for pt in tct.peaks[key]:
plt.plot(pt[0],pt[1],'r*')
for pt in tct.valleys[key]:
plt.plot(pt[0],pt[1],'b*')
plt.grid()
plt.show()
disp = Display((800,600))
while disp.isNotDone():
img = cam.getImage()
result = tct.recognize(img)
plt.plot(tct._rtData,'r-')
plt.grid()
plt.savefig('temp.png')
plt.clf()
plotImg = Image('temp.png')
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
roi.draw(width=3)
img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
img = img.applyLayers()<|fim▁hole|><|fim▁end|> | img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5)
img.save(disp) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
<|fim▁hole|> physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator<|fim▁end|> | except ValueError:
try: # See if the function writer specified a physical type |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
<|fim_middle|>
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | """
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
<|fim_middle|>
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | """
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0]))) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
<|fim_middle|>
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | @classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
<|fim_middle|>
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
<|fim_middle|>
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
<|fim_middle|>
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
<|fim_middle|>
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_ |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
<|fim_middle|>
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | return |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
<|fim_middle|>
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | break |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
<|fim_middle|>
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | error_msg = "a 'unit' attribute without an 'is_equivalent' method" |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
<|fim_middle|>
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | error_msg = "no 'unit' attribute" |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
<|fim_middle|>
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0]))) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
<|fim_middle|>
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets])) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
<|fim_middle|>
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0]))) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
<|fim_middle|>
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | return self(func) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
<|fim_middle|>
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | return self |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
<|fim_middle|>
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | continue |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
<|fim_middle|>
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | bound_args.arguments[param.name] = param.default |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
<|fim_middle|>
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | targets = self.decorator_kwargs[param.name]
is_annotation = False |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
<|fim_middle|>
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | targets = param.annotation
is_annotation = True |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
<|fim_middle|>
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | continue |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
<|fim_middle|>
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | continue |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
<|fim_middle|>
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | valid_targets = [targets] |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
<|fim_middle|>
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None] |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
<|fim_middle|>
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | continue |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
<|fim_middle|>
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | valid_targets = [t for t in targets if t is not None] |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
<|fim_middle|>
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | valid_targets = targets |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
<|fim_middle|>
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))] |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
<|fim_middle|>
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | return return_.to(wrapped_signature.return_annotation) |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
<|fim_middle|>
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | return return_ |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def <|fim_middle|>(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | _get_allowed_units |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def <|fim_middle|>(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | _validate_arg_value |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def <|fim_middle|>(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | as_decorator |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def <|fim_middle|>(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | __init__ |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def <|fim_middle|>(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def wrapper(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | __call__ |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (either as strings or unit objects) and physical
types, return a list of Unit objects.
"""
allowed_units = []
for target in targets:
try: # unit passed in as a string
target_unit = Unit(target)
except ValueError:
try: # See if the function writer specified a physical type
physical_type_id = _unit_physical_mapping[target]
except KeyError: # Function argument target is invalid
raise ValueError("Invalid unit or physical type '{}'."
.format(target))
# get unit directly from physical type id
target_unit = Unit._from_physical_type_id(physical_type_id)
allowed_units.append(target_unit)
return allowed_units
def _validate_arg_value(param_name, func_name, arg, targets, equivalencies):
"""
Validates the object passed in to the wrapped function, ``arg``, with target
unit or physical type, ``target``.
"""
if len(targets) == 0:
return
allowed_units = _get_allowed_units(targets)
for allowed_unit in allowed_units:
try:
is_equivalent = arg.unit.is_equivalent(allowed_unit,
equivalencies=equivalencies)
if is_equivalent:
break
except AttributeError: # Either there is no .unit or no .is_equivalent
if hasattr(arg, "unit"):
error_msg = "a 'unit' attribute without an 'is_equivalent' method"
else:
error_msg = "no 'unit' attribute"
raise TypeError("Argument '{}' to function '{}' has {}. "
"You may want to pass in an astropy Quantity instead."
.format(param_name, func_name, error_msg))
else:
if len(targets) > 1:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to one of: {}."
.format(param_name, func_name,
[str(targ) for targ in targets]))
else:
raise UnitsError("Argument '{}' to function '{}' must be in units"
" convertible to '{}'."
.format(param_name, func_name,
str(targets[0])))
class QuantityInput:
@classmethod
def as_decorator(cls, func=None, **kwargs):
r"""
A decorator for validating the units of arguments to functions.
Unit specifications can be provided as keyword arguments to the decorator,
or by using function annotation syntax. Arguments to the decorator
take precedence over any function annotations present.
A `~astropy.units.UnitsError` will be raised if the unit attribute of
the argument is not equivalent to the unit specified to the decorator
or in the annotation.
If the argument has no unit attribute, i.e. it is not a Quantity object, a
`ValueError` will be raised unless the argument is an annotation. This is to
allow non Quantity annotations to pass through.
Where an equivalency is specified in the decorator, the function will be
executed with that equivalency in force.
Notes
-----
The checking of arguments inside variable arguments to a function is not
supported (i.e. \*arg or \**kwargs).
Examples
--------
.. code-block:: python
import astropy.units as u
@u.quantity_input(myangle=u.arcsec)
def myfunction(myangle):
return myangle**2
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec):
return myangle**2
Also you can specify a return value annotation, which will
cause the function to always return a `~astropy.units.Quantity` in that
unit.
.. code-block:: python
import astropy.units as u
@u.quantity_input
def myfunction(myangle: u.arcsec) -> u.deg**2:
return myangle**2
Using equivalencies::
import astropy.units as u
@u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy())
def myfunction(myenergy):
return myenergy**2
"""
self = cls(**kwargs)
if func is not None and not kwargs:
return self(func)
else:
return self
def __init__(self, func=None, **kwargs):
self.equivalencies = kwargs.pop('equivalencies', [])
self.decorator_kwargs = kwargs
def __call__(self, wrapped_function):
# Extract the function signature for the function we are wrapping.
wrapped_signature = inspect.signature(wrapped_function)
# Define a new function to return in place of the wrapped one
@wraps(wrapped_function)
def <|fim_middle|>(*func_args, **func_kwargs):
# Bind the arguments to our new function to the signature of the original.
bound_args = wrapped_signature.bind(*func_args, **func_kwargs)
# Iterate through the parameters of the original signature
for param in wrapped_signature.parameters.values():
# We do not support variable arguments (*args, **kwargs)
if param.kind in (inspect.Parameter.VAR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL):
continue
# Catch the (never triggered) case where bind relied on a default value.
if param.name not in bound_args.arguments and param.default is not param.empty:
bound_args.arguments[param.name] = param.default
# Get the value of this parameter (argument to new function)
arg = bound_args.arguments[param.name]
# Get target unit or physical type, either from decorator kwargs
# or annotations
if param.name in self.decorator_kwargs:
targets = self.decorator_kwargs[param.name]
is_annotation = False
else:
targets = param.annotation
is_annotation = True
# If the targets is empty, then no target units or physical
# types were specified so we can continue to the next arg
if targets is inspect.Parameter.empty:
continue
# If the argument value is None, and the default value is None,
# pass through the None even if there is a target unit
if arg is None and param.default is None:
continue
# Here, we check whether multiple target unit/physical type's
# were specified in the decorator/annotation, or whether a
# single string (unit or physical type) or a Unit object was
# specified
if isinstance(targets, str) or not isiterable(targets):
valid_targets = [targets]
# Check for None in the supplied list of allowed units and, if
# present and the passed value is also None, ignore.
elif None in targets:
if arg is None:
continue
else:
valid_targets = [t for t in targets if t is not None]
else:
valid_targets = targets
# If we're dealing with an annotation, skip all the targets that
# are not strings or subclasses of Unit. This is to allow
# non unit related annotations to pass through
if is_annotation:
valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))]
# Now we loop over the allowed units/physical types and validate
# the value of the argument:
_validate_arg_value(param.name, wrapped_function.__name__,
arg, valid_targets, self.equivalencies)
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(self.equivalencies):
return_ = wrapped_function(*func_args, **func_kwargs)
if wrapped_signature.return_annotation not in (inspect.Signature.empty, None):
return return_.to(wrapped_signature.return_annotation)
else:
return return_
return wrapper
quantity_input = QuantityInput.as_decorator
<|fim▁end|> | wrapper |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig<|fim▁hole|>
def ready(self):
import contentstore.signals
contentstore.signals<|fim▁end|> |
class ContentStoreAppConfig(AppConfig):
name = "contentstore" |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
class ContentStoreAppConfig(AppConfig):
<|fim_middle|>
<|fim▁end|> | name = "contentstore"
def ready(self):
import contentstore.signals
contentstore.signals |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
class ContentStoreAppConfig(AppConfig):
name = "contentstore"
def ready(self):
<|fim_middle|>
<|fim▁end|> | import contentstore.signals
contentstore.signals |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
class ContentStoreAppConfig(AppConfig):
name = "contentstore"
def <|fim_middle|>(self):
import contentstore.signals
contentstore.signals
<|fim▁end|> | ready |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,<|fim▁hole|> }
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT<|fim▁end|> | 'titles': ALL_TITLES[start_index:end_index], |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
<|fim_middle|>
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | return SELECTED_FULL_RESULTS.get(title_number) |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
<|fim_middle|>
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
} |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
<|fim_middle|>
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | return _get_titles(page_number) |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
<|fim_middle|>
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | return _get_titles(page_number) |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
<|fim_middle|>
<|fim▁end|> | return OFFICIAL_COPY_RESULT |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def <|fim_middle|>(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | get_title |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def <|fim_middle|>(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | _get_titles |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def <|fim_middle|>(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | get_titles_by_postcode |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def <|fim_middle|>(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | get_titles_by_address |
<|file_name|>api_client.py<|end_file_name|><|fim▁begin|>import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE)
start_index = page_number * SEARCH_RESULTS_PER_PAGE
end_index = start_index + SEARCH_RESULTS_PER_PAGE
return {
'number_pages': number_pages,
'number_results': nof_results,
'page_number': page_number,
'titles': ALL_TITLES[start_index:end_index],
}
def get_titles_by_postcode(postcode, page_number):
return _get_titles(page_number)
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def <|fim_middle|>(title_number):
return OFFICIAL_COPY_RESULT
<|fim▁end|> | get_official_copy_data |
<|file_name|>number_arabic.py<|end_file_name|><|fim▁begin|>#
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dragonfly is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Dragonfly. If not, see
# <http://www.gnu.org/licenses/>.
#
"""
Arabic language implementations of Integer and Digits classes
============================================================================
"""
from ..base.integer_internal import (MapIntBuilder, CollectionIntBuilder,
MagnitudeIntBuilder, IntegerContentBase)
from ..base.digits_internal import DigitsContentBase
#---------------------------------------------------------------------------
int_0 = MapIntBuilder({
"صفر": 0,
})
int_1_9 = MapIntBuilder({
"واحد": 1,
"اثنان": 2,
"ثلاثة": 3,
"اربعة": 4,
"خمسة": 5,
"ستة": 6,
"سبعة": 7,
"ثمانية": 8,
"تسعة": 9,
})
int_10_19 = MapIntBuilder({
"عشرة": 10,
"احدى عشر": 11,
"اثنا عشر": 12,
"ثلاثة عشر": 13,
"اربعة عشر": 14,
"خمسة عشر": 15,
"ستة عشر": 16,
"سبعة عشر": 17,
"ثمانية عشر": 18,
"تسعة عشر": 19,
})
int_20_90_10 = MapIntBuilder({
"عشرون": 2,
"ثلاثون": 3,
"اربعون": 4,
"خمسون": 5,
"ستون": 6,
"سبعون": 7,
"ثمانون": 8,
"تسعون": 9,
})
int_20_99 = MagnitudeIntBuilder(
factor = 10,
spec = "<multiplier> [<remainder>]",
multipliers = [int_20_90_10],
remainders = [int_1_9],
)
int_and_1_99 = CollectionIntBuilder(
<|fim▁hole|> set = [int_1_9, int_10_19, int_20_99],
)
int_100s = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_1_9],
remainders = [int_and_1_99],
)
int_100big = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_10_19, int_20_99],
remainders = [int_و_1_99]
)
int_1000s = MagnitudeIntBuilder(
factor = 1000,
spec = "[<multiplier>] thousand [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s],
remainders = [int_و_1_99, int_100s]
)
int_1000000s = MagnitudeIntBuilder(
factor = 1000000,
spec = "[<multiplier>] million [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s, int_1000s],
remainders = [int_و_1_99, int_100s, int_1000s],
)
#---------------------------------------------------------------------------
class IntegerContent(IntegerContentBase):
builders = [int_0, int_1_9, int_10_19, int_20_99,
int_100s, int_100big, int_1000s, int_1000000s]
class DigitsContent(DigitsContentBase):
digits = [("صفر", "اووه"), "واحد", "اثنان", "ثلاثة", "اربعة",
"خمسة", "ستة", "سبعة", "ثمانية", "تسعة"]<|fim▁end|> | spec = "[و] <element>",
|
<|file_name|>number_arabic.py<|end_file_name|><|fim▁begin|>#
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dragonfly is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Dragonfly. If not, see
# <http://www.gnu.org/licenses/>.
#
"""
Arabic language implementations of Integer and Digits classes
============================================================================
"""
from ..base.integer_internal import (MapIntBuilder, CollectionIntBuilder,
MagnitudeIntBuilder, IntegerContentBase)
from ..base.digits_internal import DigitsContentBase
#---------------------------------------------------------------------------
int_0 = MapIntBuilder({
"صفر": 0,
})
int_1_9 = MapIntBuilder({
"واحد": 1,
"اثنان": 2,
"ثلاثة": 3,
"اربعة": 4,
"خمسة": 5,
"ستة": 6,
"سبعة": 7,
"ثمانية": 8,
"تسعة": 9,
})
int_10_19 = MapIntBuilder({
"عشرة": 10,
"احدى عشر": 11,
"اثنا عشر": 12,
"ثلاثة عشر": 13,
"اربعة عشر": 14,
"خمسة عشر": 15,
"ستة عشر": 16,
"سبعة عشر": 17,
"ثمانية عشر": 18,
"تسعة عشر": 19,
})
int_20_90_10 = MapIntBuilder({
"عشرون": 2,
"ثلاثون": 3,
"اربعون": 4,
"خمسون": 5,
"ستون": 6,
"سبعون": 7,
"ثمانون": 8,
"تسعون": 9,
})
int_20_99 = MagnitudeIntBuilder(
factor = 10,
spec = "<multiplier> [<remainder>]",
multipliers = [int_20_90_10],
remainders = [int_1_9],
)
int_and_1_99 = CollectionIntBuilder(
spec = "[و] <element>",
set = [int_1_9, int_10_19, int_20_99],
)
int_100s = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_1_9],
remainders = [int_and_1_99],
)
int_100big = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_10_19, int_20_99],
remainders = [int_و_1_99]
)
int_1000s = MagnitudeIntBuilder(
factor = 1000,
spec = "[<multiplier>] thousand [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s],
remainders = [int_و_1_99, int_100s]
)
int_1000000s = MagnitudeIntBuilder(
factor = 1000000,
spec = "[<multiplier>] million [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s, int_1000s],
remainders = [int_و_1_99, int_100s, int_1000s],
)
#---------------------------------------------------------------------------
class IntegerContent(IntegerContentBase):
builders = [int_0, int_1_9, int_10_19, int_20_99,
int_100s, int_100big, int_1000s, int_1000000s]
class DigitsContent(DigitsContentBase):
<|fim_middle|>
سعة"]<|fim▁end|> | digits = [("صفر", "اووه"), "واحد", "اثنان", "ثلاثة", "اربعة",
"خمسة", "ستة", "سبعة", "ثمانية", "ت |
<|file_name|>number_arabic.py<|end_file_name|><|fim▁begin|>#
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dragonfly is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Dragonfly. If not, see
# <http://www.gnu.org/licenses/>.
#
"""
Arabic language implementations of Integer and Digits classes
============================================================================
"""
from ..base.integer_internal import (MapIntBuilder, CollectionIntBuilder,
MagnitudeIntBuilder, IntegerContentBase)
from ..base.digits_internal import DigitsContentBase
#---------------------------------------------------------------------------
int_0 = MapIntBuilder({
"صفر": 0,
})
int_1_9 = MapIntBuilder({
"واحد": 1,
"اثنان": 2,
"ثلاثة": 3,
"اربعة": 4,
"خمسة": 5,
"ستة": 6,
"سبعة": 7,
"ثمانية": 8,
"تسعة": 9,
})
int_10_19 = MapIntBuilder({
"عشرة": 10,
"احدى عشر": 11,
"اثنا عشر": 12,
"ثلاثة عشر": 13,
"اربعة عشر": 14,
"خمسة عشر": 15,
"ستة عشر": 16,
"سبعة عشر": 17,
"ثمانية عشر": 18,
"تسعة عشر": 19,
})
int_20_90_10 = MapIntBuilder({
"عشرون": 2,
"ثلاثون": 3,
"اربعون": 4,
"خمسون": 5,
"ستون": 6,
"سبعون": 7,
"ثمانون": 8,
"تسعون": 9,
})
int_20_99 = MagnitudeIntBuilder(
factor = 10,
spec = "<multiplier> [<remainder>]",
multipliers = [int_20_90_10],
remainders = [int_1_9],
)
int_and_1_99 = CollectionIntBuilder(
spec = "[و] <element>",
set = [int_1_9, int_10_19, int_20_99],
)
int_100s = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_1_9],
remainders = [int_and_1_99],
)
int_100big = MagnitudeIntBuilder(
factor = 100,
spec = "[<multiplier>] hundred [<remainder>]",
multipliers = [int_10_19, int_20_99],
remainders = [int_و_1_99]
)
int_1000s = MagnitudeIntBuilder(
factor = 1000,
spec = "[<multiplier>] thousand [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s],
remainders = [int_و_1_99, int_100s]
)
int_1000000s = MagnitudeIntBuilder(
factor = 1000000,
spec = "[<multiplier>] million [<remainder>]",
multipliers = [int_1_9, int_10_19, int_20_99, int_100s, int_1000s],
remainders = [int_و_1_99, int_100s, int_1000s],
)
#---------------------------------------------------------------------------
class IntegerContent(IntegerContentBase):
builders = [int_0, int_1_9, int_10_19, int_20_99,
int_100s, int_100big, int_1000s, int_1000000s]
class DigitsContent(DigitsContentBase):
digits = [("صفر", "اووه"), "واحد", "اثنان", "ثلاثة", "اربعة",
"خمسة", "ستة", "سبعة", "ثمانية", "تسعة"]<|fim_middle|>
<|fim▁end|> | |
<|file_name|>test_script_delete.py<|end_file_name|><|fim▁begin|><|fim▁hole|>FOLDERPATH = sys.argv[1]
#os.chdir(FOLDERPATH)
walk = os.walk(FOLDERPATH)
FSEVENT = "delete"
for item in walk:
FILEPATHPREFIX = item[0] + "\\"
for song in item[2]:
if song.endswith(".mp3"):
FILEPATH = "%s%s" % (FILEPATHPREFIX, song)
os.system('python script.py "' + song + '" "' + FILEPATH + '" "' + FSEVENT + '"')<|fim▁end|> | import os
import time
import sys
|
<|file_name|>test_script_delete.py<|end_file_name|><|fim▁begin|>import os
import time
import sys
FOLDERPATH = sys.argv[1]
#os.chdir(FOLDERPATH)
walk = os.walk(FOLDERPATH)
FSEVENT = "delete"
for item in walk:
FILEPATHPREFIX = item[0] + "\\"
for song in item[2]:
if song.endswith(".mp3"):
FI <|fim_middle|>
<|fim▁end|> | LEPATH = "%s%s" % (FILEPATHPREFIX, song)
os.system('python script.py "' + song + '" "' + FILEPATH + '" "' + FSEVENT + '"') |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)<|fim▁hole|> self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()<|fim▁end|> |
def visit_BasicNodeReplacement(self, node): |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
<|fim_middle|>
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | _fields = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
<|fim_middle|>
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | _fields = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
<|fim_middle|>
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | _fields = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
<|fim_middle|>
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | _fields = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
<|fim_middle|>
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | _fields = [
('child', tree.Node, 'OPTIONAL'),
] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
<|fim_middle|>
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | """Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
<|fim_middle|>
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!") |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
<|fim_middle|>
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | super().__init__()
self.visited = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
<|fim_middle|>
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.visited.append(node.__class__.__name__)
super().generic_visit(node) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
<|fim_middle|>
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.visited.append("visited Copy!") |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
<|fim_middle|>
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
<|fim_middle|>
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | super().__init__()
self.recorded_access_path = None |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
<|fim_middle|>
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.recorded_access_path = self.access_path[:] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
<|fim_middle|>
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | pass |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
<|fim_middle|>
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
<|fim_middle|>
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | super().__init__()
self.visited = [] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
<|fim_middle|>
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.visited.append(node.__class__.__name__)
return super().generic_visit(node) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
<|fim_middle|>
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.visited.append("visited Copy!")
return node |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
<|fim_middle|>
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
<|fim_middle|>
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | super().__init__()
self.recorded_access_path = None |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
<|fim_middle|>
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | self.recorded_access_path = self.access_path[:]
return node |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
<|fim_middle|>
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
<|fim_middle|>
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | return BasicNodeReplacement() |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
<|fim_middle|>
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | return None # Delete this node |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
<|fim_middle|>
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | return self.NONE_DEPUTY # Replace this node with None |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
<|fim_middle|>
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | return [BasicNode(), BasicNodeReplacement()] |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
<|fim_middle|>
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | """py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
<|fim_middle|>
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
<|fim_middle|>
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
<|fim_middle|>
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | """py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
<|fim_middle|>
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
<|fim_middle|>
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
<|fim_middle|>
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path) |
<|file_name|>test_visitors.py<|end_file_name|><|fim▁begin|>"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# =============================================================================
# Helper classes
# =============================================================================
class BasicNode(tree.Node):
_fields = []
class BasicNodeReplacement(tree.Node):
_fields = []
class BasicNodeWithListReplacement(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class ParentNodeWithChildrenList(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# -----------------------------------------------------------------------------
# Concrete Visitors used for testing
# -----------------------------------------------------------------------------
class VisitOrderCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
class AccessPathCheckingVisitor(visitors.RecursiveNodeVisitor):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
class EmptyTransformer(visitors.RecursiveNodeTransformer):
pass
class VisitOrderCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node
class AccessPathCheckingTransformer(visitors.RecursiveNodeTransformer):
def __init__(self):
super().__init__()
self.recorded_access_path = None
def visit_BasicNode(self, node):
self.recorded_access_path = self.access_path[:]
return node
class TransformationCheckingTransformer(visitors.RecursiveNodeTransformer):
def visit_BasicNode(self, node):
return BasicNodeReplacement()
def visit_BasicNodeDeletable(self, node):
return None # Delete this node
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None
def visit_BasicNodeWithListReplacement(self, node):
return [BasicNode(), BasicNodeReplacement()]
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
class TestRecursiveASTVisitor(Test):
"""py2c.tree.visitors.RecursiveNodeVisitor
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path)
class TestRecursiveASTTransformer(Test):
"""py2c.tree.visitors.RecursiveNodeTransformer
"""
context = globals()
@data_driven_test("visitors-visitor_order.yaml", prefix="empty transformer does not transform ")
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("visitors-visitor_order.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("visitors-access_path.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
<|fim_middle|>
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
<|fim▁end|> | to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.