Code Monkey home page Code Monkey logo

sexpdata's Introduction

S-expression parser for Python

sexpdata is a simple S-expression parser/serializer. It has simple load and dump functions like pickle, json or PyYAML module.

>>> from sexpdata import loads, dumps
>>> loads('("a" "b")')
['a', 'b']
>>> print(dumps(['a', 'b']))
("a" "b")

You can install sexpdata from PyPI:

pip install sexpdata

Links:

Making a release

1. python -m build 1. twine check dist/* 1. git tag v1.0.x 1. twine upload dist/*

License

sexpdata is licensed under the terms of the BSD 2-Clause License. See the source code for more information.

sexpdata's People

Contributors

dlitz avatar efokken-abb avatar graingert avatar immerrr avatar jd-boyd avatar lenianiva avatar mgorny avatar mmmspatz avatar tkf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sexpdata's Issues

Symbol to string

how does one convert a symbol to a string? Like:

str(Symbol('App')) -> 'App'

is there a clean way to do this? Currently calling str() on symbol doesn't help and equalities like:

term == 'App'

fail.

Ability to track token locations in input file

Would it be possible to add some kind of debug mode so that each token could be associated with line and column number in the input file?

I'm writing an tool that processes large s-expressions and it would be nice to report the location where a semantic error occurs.

Parse function quotes

E.g. #'foo

If I read the source code aright, this would be just an additional if branch after the parsing of simple quotes, e.g.

elif c == '#':
    c_next = string[i+1] if i + 1 < len(string) else None
    if not c_next or c_next != "'":  raise ExpectQuoted()
    # Proceed to parse the following simple quote
elif c == self.line_comment:
    …

What do you think?

More "\" in dumps

Hi, can we disable '\' before '.' in the result?

>> print(dumps([Symbol('a.c'), Symbol('b')]))
(a\.c b)

I want to get the result a.c b
Thanks,

Module installation via pip fails

Hello!

During the installation via pip I get the following error:

python -m pip install sexpdata
Collecting sexpdata
  Using cached sexpdata-1.0.1.tar.gz (8.6 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [75 lines of output]
      /private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `license` defined outside of `pyproject.toml` is ignored.
      !!

              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:

              `license = 'BSD License'`

              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `license` is listed as `dynamic`.

              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/

              To prevent this problem, you can list `license` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************

      !!
        _handle_missing_dynamic(dist, project_table)
      /private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `keywords` defined outside of `pyproject.toml` is ignored.
      !!

              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:

              `keywords = ['s-expression', 'lisp', 'parser']`

              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `keywords` is listed as `dynamic`.

              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/

              To prevent this problem, you can list `keywords` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************

      !!
        _handle_missing_dynamic(dist, project_table)
      Traceback (most recent call last):
        File "/Users/sanabriarusso/Desktop/eraseme/env/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
          main()
        File "/Users/sanabriarusso/Desktop/eraseme/env/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/Users/sanabriarusso/Desktop/eraseme/env/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
          return hook(config_settings)
                 ^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=['wheel'])
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires
          self.run_setup()
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 311, in run_setup
          exec(code, locals())
        File "<string>", line 8, in <module>
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/__init__.py", line 103, in setup
          return distutils.core.setup(**attrs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/_distutils/core.py", line 159, in setup
          dist.parse_config_files()
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/dist.py", line 627, in parse_config_files
          pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/pyprojecttoml.py", line 67, in apply_configuration
          return _apply(dist, config, filepath)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 56, in apply
          _apply_project_table(dist, config, root_dir)
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 82, in _apply_project_table
          corresp(dist, value, root_dir)
        File "/private/var/folders/yk/f369l6yx6890jq3z62mlkn1w0000gn/T/pip-build-env-92yauvn1/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 183, in _license
          _set_config(dist, "license", val["text"])
                                       ~~~^^^^^^^^
      KeyError: 'text'
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

Accordingly, in order to resolve this issue changes to the way project configuration is carried out. This may be done by listing license under dynamic. The same issue is raised by keywords, which in order to be considered should be inside pyproject.toml and under dynamic.

[Feature Request] Infix operators

Would it fit the theme of this package to have infix operators? For example, suppose I want the operator -> to act as an infix operator:

class Implies(Infix):
    op = '->'
parse("a -> b -> c") == Infix([Symbol("a"), Symbol("b"), Symbol("c")])

This could be done immediately upon finishing parsing a list, for example.

pip3 install sexpdata caught error

hello , my python version is 3.11.5 and pip version is pip 23.3.1

when i install via pip3 install sexpdata , i got error message blow

❯ pip3 install sexpdata
Collecting sexpdata
  Using cached sexpdata-1.0.1.tar.gz (8.6 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [75 lines of output]
      /private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `license` defined outside of `pyproject.toml` is ignored.
      !!

              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:

              `license = 'BSD License'`

              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `license` is listed as `dynamic`.

              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/

              To prevent this problem, you can list `license` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************

      !!
        _handle_missing_dynamic(dist, project_table)
      /private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `keywords` defined outside of `pyproject.toml` is ignored.
      !!

              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:

              `keywords = ['s-expression', 'lisp', 'parser']`

              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `keywords` is listed as `dynamic`.

              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/

              To prevent this problem, you can list `keywords` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************

      !!
        _handle_missing_dynamic(dist, project_table)
      Traceback (most recent call last):
        File "/opt/homebrew/Caskroom/miniconda/base/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
          main()
        File "/opt/homebrew/Caskroom/miniconda/base/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/opt/homebrew/Caskroom/miniconda/base/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
          return hook(config_settings)
                 ^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=['wheel'])
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires
          self.run_setup()
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 311, in run_setup
          exec(code, locals())
        File "<string>", line 8, in <module>
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/__init__.py", line 103, in setup
          return distutils.core.setup(**attrs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/_distutils/core.py", line 159, in setup
          dist.parse_config_files()
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/dist.py", line 627, in parse_config_files
          pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/pyprojecttoml.py", line 67, in apply_configuration
          return _apply(dist, config, filepath)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 56, in apply
          _apply_project_table(dist, config, root_dir)
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 82, in _apply_project_table
          corresp(dist, value, root_dir)
        File "/private/var/folders/fj/31b93k8j72b0723dj4cj4vk00000gn/T/pip-build-env-rawt4j2c/overlay/lib/python3.11/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 183, in _license
          _set_config(dist, "license", val["text"])
                                       ~~~^^^^^^^^
      KeyError: 'text'
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

but if i use pip3 install sexpdata==1.0.0 , i will get no error and installed successful

Please support loading multiple objects

I would like to be able to load a file like this:

(define (a b c) 5)

(define (d e f) (+ e f))

When I try, I get:

  File "/home/jdboyd/.virtualenvs/pypile/lib/python3.3/site-packages/sexpdata.py", line 244, in loads
    assert len(obj) == 1  # FIXME: raise an appropriate error
AssertionError

I don't think there is an appropriate error to raise there since I think it should be able to parse that file.

If I patch the code to also export the parse function, I can get the above example file returned as a list like:

[[Symbol('define'), [Symbol('a'), Symbol('b'), Symbol('c')], 5], [Symbol('define'), [Symbol('d'), Symbol('e'), Symbol('f')], [Symbol('+'), Symbol('e'), Symbol('f')]]]

This is more useful than the assert. If the assert is important to some users, perhaps it could only be triggered when a single_express kwarg is set?

Remove setup.py?

It is replaced by pyproject.toml, right?

Need to see what implication is for oldest supported pythons.

recover original json from sexpdata dump

Original json record

#+begin_src python
{'ExifTool:ExifToolVersion': 12.4,
'File:ColumnCount': 91,
'File:Delimiter': ',',
'File:Directory': '/home/vanangamudi/ko-pa-ni',
'File:FileAccessDate': '2023:12:18 13:32:27+05:30',
'File:FileInodeChangeDate': '2023:12:16 15:04:02+05:30',
'File:FileModifyDate': '2021:05:12 23:42:00+05:30',
'File:FileName': 'exifinfo.csv',
'File:FilePermissions': 100777,
'File:FileSize': 34064,
'File:FileType': 'CSV',
'File:FileTypeExtension': 'CSV',
'File:MIMEEncoding': 'us-ascii',
'File:MIMEType': 'text/csv',
'File:Newlines': '\n',
'File:Quoting': '"',
'File:RowCount': 73,
'SourceFile': '/home/vanangamudi/ko-pa-ni/exifinfo.csv',
'_id': ObjectId('658068a0b760ac3daf951f44')}
#+end_src

#+begin_src lisp
(:SourceFile "/home/vanangamudi/ko-pa-ni/exifinfo.csv"
:ExifTool:ExifToolVersion 12.4
:FileName "exifinfo.csv"
:File:Directory "/home/vanangamudi/ko-pa-ni"
:File:FileSize 34064
:File:FileModifyDate "2021:05:12 23:42:00+05:30"
:File:FileAccessDate "2023:12:18 13:32:27+05:30"
:File:FileInodeChangeDate "2023:12:16 15:04:02+05:30"
:File:FilePermissions 100777
:File:FileType "CSV"
:File:FileTypeExtension "CSV"
:File:MIMEType "text/csv"
:File:MIMEEncoding "us-ascii"
:File:Newlines "\n"
:File:Delimiter ","
:File:Quoting """
:File:ColumnCount 91
:File:RowCount 73)
#+end_src

loaded data from sexpdata

#+begin_src python
[Symbol(':SourceFile'), '/home/vanangamudi/ko-pa-ni/exifinfo.csv',
Symbol(':ExifTool:ExifToolVersion'), 12.4,
Symbol(':File:FileName'), 'exifinfo.csv',
Symbol(':File:Directory'), '/home/vanangamudi/ko-pa-ni',
Symbol(':File:FileSize'), 34064,
Symbol(':File:FileModifyDate'), '2021:05:12 23:42:00+05:30',
Symbol(':File:FileAccessDate'), '2023:12:18 13:32:27+05:30',
Symbol(':File:FileInodeChangeDate'), '2023:12:16 15:04:02+05:30',
Symbol(':File:FilePermissions'), 100777,
Symbol(':File:FileType'), 'CSV',
Symbol(':File:FileTypeExtension'), 'CSV',
Symbol(':File:MIMEType'), 'text/csv',
Symbol(':File:MIMEEncoding'), 'us-ascii',
Symbol(':File:Newlines'), '\n',
Symbol(':File:Delimiter'), ',',
Symbol(':File:Quoting'), '"',
Symbol(':File:ColumnCount'), 91,
Symbol(':File:RowCount'), 73]
#+end_src

I need to convert this into original json. is there a function already for this?

Can't load a dictionary

It's possible to dump a dict to a symbolic expression:

In [2]: dumps({'a': 1})
Out[2]: '(:a 1)'

Unfortunately, getting a dictionary back is not possible:

In [5]: {'a': 1} == loads(dumps({'a': 1}))
Out[5]: False

The issue here seems to be that the parser doesn't understand that symbols starting with colon are supposed to be keys:

In [6]: loads(dumps({'a': 1}))
Out[6]: [Symbol(':a'), 1]

I tested in Python 3 but Python 2 has the same problem:

In [3]: loads(dumps({'a': 1}))
Out[3]: [Symbol(u':a'), 1]

unexpected parsing error

I had an unexpected error when parsing a (string) s-expression into a nested array/lists representing the AST. The s-expression comes from (SerAPI https://github.com/ejgallego/coq-serapi), but it looks fine to me:

sexp = b'(Answer 3(ObjList((CoqGoal((fg_goals(((name 3)(ty(App(Ind(((Mutind(MPfile(DirPath((Id Logic)(Id Init)(Id Coq))))(DirPath())(Id eq))0)(Instance())))((Ind(((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id bool))0)(Instance())))(App(Const((Constant(MPfile(DirPath((Id Nat)(Id Init)(Id Coq))))(DirPath())(Id odd))(Instance())))((App(Construct((((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id nat))0)2)(Instance())))((Construct((((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id nat))0)1)(Instance())))))))(Construct((((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id bool))0)1)(Instance()))))))(hyp()))))(bg_goals())(shelved_goals())(given_up_goals()))))))\n'

When I try to parse that I get the following error message:

train(policy,optimizer,env,gamma,nb_episodes=nb_episodes,ema_alpha=ema_alpha)
  File "main.py", line 88, in train
    state, reward, done, _ = env.step('Example test_oddb1: Nat.odd 1 = true.')
  File "/Users/korkejudith/home_simulation_research/coq-serapi-python/python_api/coq_env.py", line 120, in step
    state = self.state_embedder(state)
  File "/Users/korkejudith/home_simulation_research/coq-serapi-python/python_api/ai_mathematician.py", line 33, in __call__
    psexp = loads(str(sexp))
  File "/Users/korkejudith/miniconda3/envs/rltp/lib/python3.6/site-packages/sexpdata.py", line 243, in loads
    obj = parse(string, **kwds)
  File "/Users/korkejudith/miniconda3/envs/rltp/lib/python3.6/site-packages/sexpdata.py", line 675, in parse
    return Parser(string, **kwds).parse()
  File "/Users/korkejudith/miniconda3/envs/rltp/lib/python3.6/site-packages/sexpdata.py", line 655, in parse
    (i, sexp) = self.parse_sexp(0)
  File "/Users/korkejudith/miniconda3/envs/rltp/lib/python3.6/site-packages/sexpdata.py", line 641, in parse_sexp
    (i, subsexp) = self.parse_sexp(i + 1)
  File "/Users/korkejudith/miniconda3/envs/rltp/lib/python3.6/site-packages/sexpdata.py", line 642, in parse_sexp
    append(Quoted(subsexp[0]))
IndexError: list index out of range


Code to reproduce the error:

    sexp = ''' (Answer 3(ObjList((CoqGoal((fg_goals(((name 3)(ty(Prod(Name(Id n))(Ind(((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id nat))0)(Instance())))(App(Ind(((Mutind(MPfile(DirPath((Id Logic)(Id Init)(Id Coq))))(DirPath())(Id eq))0)(Instance())))((Ind(((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id nat))0)(Instance())))(App(Const((Constant(MPfile(DirPath((Id Nat)(Id Init)(Id Coq))))(DirPath())(Id add))(Instance())))((Construct((((Mutind(MPfile(DirPath((Id Datatypes)(Id Init)(Id Coq))))(DirPath())(Id nat))0)1)(Instance())))(Rel 1)))(Rel 1)))))(hyp()))))(bg_goals())(shelved_goals())(given_up_goals()))))))'
    '''
    psexp = loads(sexp)

Example of monkey patching to match KiCad EDA pretty print

KiCad EDA indents sexp contextually. Thus, the prettyfier requires a Symbol stack to decide whether to break or not.

from sexpdata import loads, dumps, tosexp, Delimiters, Symbol



ROUND_2_SYMBOLS = ('at',)

@tosexp.register(float)
def _(obj, **kwds):
    if kwds['car_stack'][-1] in ROUND_2_SYMBOLS:
        _ = round(obj, 2)
        return f'{_:.2f}'
    return str(obj)



BREAK_OPENER_SYMBOLS = ('symbol', 'property', 'effects', 'pin', 'name', 'number', 'rectangle', 'stroke', 'fill')
BREAK_CLOSER_SYMBOLS = ('kicad_symbol_lib', 'symbol', 'property', 'pin', 'rectangle')
BREAK_PREFIX_SYMBOLS = ('kicad_symbol_lib',)

def dont_break(car_stack, str_car):
    return (str_car == 'effects' and car_stack[-1] in ('name', 'number'))

@tosexp.register(Delimiters)
def _(self, **kwds):
    expr_separator = ' '
    exprs_indent = ''
    break_prefix_opener = ''
    break_prefix_closer = ''
    suffix_break = ''

    car = self.I[0]
    if isinstance(car, Symbol):
        str_car = str(car)
        kwds.setdefault('car_stack', [])
        if str_car in BREAK_OPENER_SYMBOLS and not dont_break(kwds['car_stack'], str_car):
            exprs_indent = '  '
            break_prefix_opener = '\n' + exprs_indent
        if str_car in BREAK_CLOSER_SYMBOLS:
            break_prefix_closer = '\n' + exprs_indent
        kwds['car_stack'].append(str_car)
        if str_car in BREAK_PREFIX_SYMBOLS:
            suffix_break = '\n'

    exprs = expr_separator.join(tosexp(x, **kwds) for x in self.I)
    indented_exprs = '\n'.join(exprs_indent + line.rstrip() for line in exprs.splitlines(True))
    indented_exprs = indented_exprs[len(exprs_indent):]

    if kwds.get('car_stack', None):
        kwds['car_stack'].pop()

    return (
        break_prefix_opener + self.__class__.opener +
        indented_exprs +
        break_prefix_closer + self.__class__.closer + suffix_break
    )

sexpdata.dumps(tree, pretty_print=True) produces strange output with big data

when i use sexpdata to read eeschem-files (like https://github.com/snhobbs/eeschema-script-control does) that include images, then writing this sexpdata back to a new file renders it useless for eeschem (https://www.kicad.org/discover/schematic-capture/).

the problem is, that whiel eeschem puts the image in many lines, the sexpdata.dumps(tree, pretty_print=True) dose not. or in short, the CR and/or LF are missing.

its easy to see in the picture:
Screenshot from 2024-07-02 23-27-29

top is the original file and bottom is the read into sexpdata and write again file.

[Bug] Pip install fails with `_MissingDynamic: `license` defined outside of `pyproject.toml` is ignored.`

pip install sexpdata fails with:
_MissingDynamic: `license` defined outside of `pyproject.toml` is ignored.

This is in python 3.10.13

$ pip install sexpdata
Collecting sexpdata
  Using cached sexpdata-1.0.1.tar.gz (8.6 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error
  
  × Getting requirements to build wheel did not run successfully.
  Γöé exit code: 1
  Γò░ΓöÇ> [69 lines of output]
      /tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `license` defined outside of `pyproject.toml` is ignored.
      !!
      
              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:
      
              `license = BSD License`
      
              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `license` is listed as `dynamic`.
      
              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
      
              To prevent this problem, you can list `license` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************
      
      !!
        _handle_missing_dynamic(dist, project_table)
      /tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/_apply_pyprojecttoml.py:75: _MissingDynamic: `keywords` defined outside of `pyproject.toml` is ignored.
      !!
      
              ********************************************************************************
              The following seems to be defined outside of `pyproject.toml`:
      
              `keywords = [s-expression, lisp, parser]`
      
              According to the spec (see the link below), however, setuptools CANNOT
              consider this value unless `keywords` is listed as `dynamic`.
      
              https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
      
              To prevent this problem, you can list `keywords` under `dynamic` or alternatively
              remove the `[project]` table from your file and rely entirely on other means of
              configuration.
              ********************************************************************************
      
      !!
        _handle_missing_dynamic(dist, project_table)
      Traceback (most recent call last):
        File "/home/aradox/.pyenv/versions/3.10.13/envs/dev/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
          main()
        File "/home/aradox/.pyenv/versions/3.10.13/envs/dev/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
          json_out[return_val] = hook(**hook_input[kwargs])
        File "/home/aradox/.pyenv/versions/3.10.13/envs/dev/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
          return hook(config_settings)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=[wheel])
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires
          self.run_setup()
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 311, in run_setup
          exec(code, locals())
        File "<string>", line 8, in <module>
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/__init__.py", line 103, in setup
          return distutils.core.setup(**attrs)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/_distutils/core.py", line 159, in setup
          dist.parse_config_files()
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/dist.py", line 627, in parse_config_files
          pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/pyprojecttoml.py", line 67, in apply_configuration
          return _apply(dist, config, filepath)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 56, in apply
          _apply_project_table(dist, config, root_dir)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 82, in _apply_project_table
          corresp(dist, value, root_dir)
        File "/tmp/pip-build-env-55j1wh1g/overlay/lib/python3.10/site-packages/setuptools/config/_apply_pyprojecttoml.py", line 183, in _license
          _set_config(dist, "license", val["text"])
      KeyError: text
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
Γöé exit code: 1
Γò░ΓöÇ> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

0.0.4 doesn't have value field anymore?

ObjList
(Pdb)     print(_local_ctx_and_goals[0].value())
*** AttributeError: 'Symbol' object has no attribute 'value'

code

    import sexpdata
    from sexpdata import Symbol

    _local_ctx_and_goals = [Symbol('ObjList'), []]
    print(_local_ctx_and_goals)
    print(_local_ctx_and_goals[0])
    print(_local_ctx_and_goals[0].value())
    print(type(_local_ctx_and_goals[0]))
    print(sexpdata.__version__)
    print()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.