2bam

C# n-tuple class generator (In Python3 of course)

Aug 29th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import inflect
  2. import re
  3.  
  4. MAX_NUMBER = 20
  5. p = inflect.engine()
  6.  
  7. def ord_name(x, firstCap):
  8.     dirty = p.number_to_words(p.ordinal(x))
  9.     clean = re.sub(r'[^a-zA-Z]+', ' ', dirty)
  10.     return ''.join([ x.capitalize() if i>0 or firstCap else x.lower() for i, x in enumerate(clean.split(' '))])
  11.  
  12. fmt_file = """
  13. // File generated
  14.  
  15. {tuples}
  16.  
  17. public static class Tuple {{
  18.     {factories}
  19. }}
  20. """
  21.  
  22. fmt_tuple = """
  23. public class Tuple<{}> {{
  24.     {}
  25.     internal Tuple({})
  26.     {{
  27.         {}
  28.     }}
  29. }}
  30. """
  31.  
  32.  
  33. fmt_factory = """
  34.     public static Tuple<{}> New<{}>({})
  35.     {{
  36.         return new Tuple<{}>({});
  37.     }}
  38. """
  39.  
  40. tuples = ""
  41. factories = ""
  42.  
  43. gen_args, props, params_sig, params_name, assign, factory = '', '', '', '', '', ''
  44.  
  45. for i in range(1, MAX_NUMBER+1):
  46.     def non_first(x):
  47.         return x if i != 1 else ''
  48.  
  49.     gen_args    += non_first(', ')      + 'T{}'.format(i)
  50.     props       += non_first('\n\t')    + 'public T{}\t{}\t{{ get; private set; }}'.format(i, ord_name(i, firstCap=True))
  51.     params_sig  += non_first(', ')      + 'T{} {}'.format(i, ord_name(i, firstCap=False))
  52.     params_name += non_first(', ')      + ord_name(i, firstCap=False)
  53.     assign      += non_first('\n\t\t')  + '{}\t= {};'.format(ord_name(i, firstCap=True), ord_name(i, firstCap=False))
  54.  
  55.     tuples      += fmt_tuple.format(gen_args, props, params_sig, assign)
  56.  
  57.     factory = fmt_factory.format(gen_args, gen_args, params_sig, gen_args, params_name)
  58.     factories += factory
  59.  
  60.     print(i)
  61.  
  62. with open('Tuple_x{}.cs'.format(MAX_NUMBER), 'w') as f:
  63.     f.write(fmt_file.format(tuples=tuples, factories=factories))
  64.  
  65. print('Done')
Advertisement
Add Comment
Please, Sign In to add comment