├── example_anymous_func.py ├── gostyle ├── __init__.py ├── _anonymous_func.py ├── _switch.py ├── _defer.py ├── _check_params.py └── _go.py ├── example_defer.py ├── example_chan.py ├── example_switch.py ├── example_import_from.py ├── test_inspect.py ├── example_import.py ├── LICENSE ├── .gitignore ├── setup.py └── README.md /example_anymous_func.py: -------------------------------------------------------------------------------- 1 | from gostyle import func, af_set_var, af_get_var 2 | b = func( 3 | lambda : af_set_var("ee", 3), 4 | lambda : print(af_get_var("ee") + 4) 5 | ) 6 | b() -------------------------------------------------------------------------------- /gostyle/__init__.py: -------------------------------------------------------------------------------- 1 | # gostyle 2 | # Author: luoyusang2007(Sean Luo) 3 | from ._go import go, to, Go, startable, destination, Chan 4 | from ._defer import defer_inside, defer 5 | from ._anonymous_func import func, af_set_var, af_get_var 6 | from ._switch import sw_set_var, case, default, pass_break, switch -------------------------------------------------------------------------------- /example_defer.py: -------------------------------------------------------------------------------- 1 | from gostyle import defer_inside, defer 2 | @defer_inside 3 | def great_func(): 4 | a = [1,2,3] 5 | b = 8 6 | defer( 7 | lambda : a.append(7), 8 | lambda : print(a), 9 | lambda : print(b) 10 | ) 11 | a.append(9) 12 | return a,b 13 | print(great_func()) -------------------------------------------------------------------------------- /example_chan.py: -------------------------------------------------------------------------------- 1 | import time 2 | from gostyle import go, Chan 3 | chan1 = Chan() 4 | def test_thread(title:str): 5 | for cnt in range(10): 6 | chan1<=cnt 7 | time.sleep(1) 8 | print(title) 9 | def chan_reader(): 10 | while True : 11 | print(chan1()) 12 | # Start the thread 13 | go(test_thread)("Call") 14 | chan_reader() -------------------------------------------------------------------------------- /gostyle/_anonymous_func.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | def af_set_var(name,val, layer = 2): 4 | stack = inspect.stack() 5 | inspect.getargvalues(stack[layer].frame).locals[name]=val 6 | 7 | def af_get_var(name, layer = 2): 8 | stack = inspect.stack() 9 | return inspect.getargvalues(stack[layer].frame).locals[name] 10 | 11 | def func(*args): 12 | def _(): 13 | for func_ in args: 14 | func_() 15 | return _ 16 | -------------------------------------------------------------------------------- /example_switch.py: -------------------------------------------------------------------------------- 1 | from gostyle import switch,case, default, sw_set_var 2 | 3 | 4 | a=4 5 | outer_var="Switch" 6 | 7 | 8 | 9 | # Return and 10 | switch(a,{ 11 | case(3):( 12 | lambda : print(outer_var + "3") 13 | ), 14 | case(4):( 15 | lambda : print(outer_var + "04"), 16 | lambda : sw_set_var("outer_var", "SSSSSSwitch"), 17 | lambda : print(outer_var + "4"), 18 | lambda : print(outer_var + "44") 19 | ), 20 | default:( 21 | lambda : print("default") 22 | ) 23 | }) 24 | 25 | print(outer_var) -------------------------------------------------------------------------------- /example_import_from.py: -------------------------------------------------------------------------------- 1 | import time 2 | from gostyle import go 3 | 4 | 5 | # If set deamonize=false, Problems will occur. Because in windows, the thread can not accept Ctrl-C keyboard interrupt. 6 | @go.goable() 7 | def test_thread(title:str): 8 | while True: 9 | time.sleep(1) 10 | print(title) 11 | 12 | 13 | 14 | 15 | 16 | if __name__ == "__main__": 17 | go.test_thread("gostylegostylegostyle;") 18 | go.test_thread("go2go2go2go2gostyle;") 19 | go(test_thread)("callcall;") 20 | test_thread("mainmainmain;") 21 | 22 | 23 | 24 | # TODO: 25 | # Single Instance support 26 | # Yield Support 27 | # Multithreading Support 28 | -------------------------------------------------------------------------------- /gostyle/_switch.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | import inspect 3 | def sw_set_var(name,val, layer = 3): 4 | stack = inspect.stack() 5 | inspect.getargvalues(stack[layer].frame).locals[name]=val 6 | def _empty_func(): 7 | pass 8 | case = lambda _:_ 9 | class Default: 10 | pass 11 | default = Default 12 | pass_break = () 13 | def switch(value, cases_dict:OrderedDict): 14 | _default = cases_dict.get(default,_empty_func) 15 | func_or_tuple = cases_dict.get(value, _default) 16 | if callable(func_or_tuple): 17 | func_or_tuple() 18 | elif type(func_or_tuple) in [tuple,list]: 19 | for func in func_or_tuple: 20 | func() 21 | 22 | 23 | -------------------------------------------------------------------------------- /gostyle/_defer.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | import inspect 3 | 4 | def defer_inside(f): 5 | @wraps(f) 6 | def wrapper(*args, **kargs): 7 | try : 8 | ret_val = f(*args, **kargs) 9 | except Exception as e: 10 | if locals().get("defer_func"): 11 | locals()["defer_func"]() 12 | raise e 13 | else: 14 | locals()["defer_func"]() # Run 15 | return ret_val 16 | return wrapper 17 | 18 | def defer(*args): 19 | def defer_runner(): 20 | for func in args: 21 | func() 22 | stack = inspect.stack() 23 | inspect.getargvalues(stack[ 2 ].frame).locals["defer_func"] = defer_runner 24 | -------------------------------------------------------------------------------- /test_inspect.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | b=3 4 | def outer_func(fun): 5 | a=1 6 | fun() 7 | called_function() 8 | print(a) 9 | 10 | 11 | def called_function(): 12 | stack = inspect.stack() 13 | print(stack) 14 | print("locals before change:", inspect.getargvalues(stack[2].frame)) 15 | inspect.getargvalues(stack[1].frame).locals["a"] = 2 16 | inspect.getargvalues(stack[2].frame).locals["b"] = 4 17 | 18 | outer_func(lambda: called_function()) 19 | print(b) 20 | 21 | 22 | 23 | 24 | # func 25 | def set_var(name,val, layer = 2): 26 | stack = inspect.stack() 27 | inspect.getargvalues(stack[layer].frame).locals[name]=val 28 | 29 | def func(func_): 30 | ee=5 31 | func_() 32 | print(locals()) 33 | 34 | 35 | func( 36 | lambda : set_var("ee", 3) 37 | ) 38 | -------------------------------------------------------------------------------- /example_import.py: -------------------------------------------------------------------------------- 1 | import time 2 | import gostyle 3 | 4 | 5 | 6 | @gostyle.destination() 7 | @gostyle.startable() 8 | def test_thread(title:str): 9 | while True: 10 | time.sleep(1) 11 | print(title) 12 | 13 | 14 | # If set deamonize=false, Problems will occur. Because in windows, the thread can not accept Ctrl-C keyboard interrupt. 15 | @gostyle.startable(forever=True) 16 | def test_thread_no_loop(title:str): 17 | time.sleep(1) 18 | print(title) 19 | 20 | 21 | if __name__ == "__main__": 22 | gostyle.to.test_thread("gostylegostylegostyle;") 23 | test_thread.start("start1start1;") 24 | test_thread_no_loop.start("start2start2") 25 | test_thread("mainmainmain;") 26 | 27 | 28 | 29 | # TODO: 30 | # Single Instance support 31 | # Yield Support 32 | # Multithreading Support 33 | -------------------------------------------------------------------------------- /gostyle/_check_params.py: -------------------------------------------------------------------------------- 1 | import datetime, time 2 | 3 | import inspect 4 | 5 | def check_str(func): 6 | def wrapper(*args, **kwargs): 7 | obj = inspect.signature(func) 8 | params = obj.parameters 9 | for k, v in enumerate(params.items()): 10 | name, param = v 11 | for i in args: 12 | if not isinstance(i, param.annotation): 13 | print("{}: {} is not string".format(name, i)) 14 | raise TypeError 15 | ret = func(*args, **kwargs) 16 | return ret 17 | return wrapper 18 | 19 | @check_str 20 | 21 | def str_add(str1:str, str2:str): 22 | t1 = datetime.datetime.now() 23 | new_str = str1 + str2 24 | time.sleep(3) 25 | delta_time = (datetime.datetime.now() - t1).total_seconds() 26 | print(new_str, round(delta_time), sep="\n") 27 | str_add(3, "4") 28 | 29 | 30 | # From:https://www.jianshu.com/p/f59667bd321c 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Luo Yusang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # IPython 77 | profile_default/ 78 | ipython_config.py 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | .dmypy.json 111 | dmypy.json 112 | 113 | # Pyre type checker 114 | .pyre/ 115 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # _*_ coding:utf-8 _*_ 2 | from setuptools import setup, find_packages 3 | 4 | with open('README.md') as fp: 5 | readme = fp.read() 6 | 7 | setup( 8 | # Necessary 9 | name='gostyle', # Module Name 10 | version='0.1.7', # Current Version 11 | description='Golang Syntax For Python', 12 | # py_modules=["my_module"], # 单文件模块写法 13 | # packages=find_packages(exclude=['contrib', 'docs', 'tests']), # 多文件模块写法 14 | packages=find_packages("gostyle"), 15 | 16 | # 以下均为可选参数 17 | long_description=readme,# 长描述 18 | long_description_content_type='text/markdown', 19 | url='https://github.com/luoyusang2007/gostyle', # 主页链接 20 | author='Luo Yusang', # 作者名 21 | author_email='luoyusang2007@hotmail.com', # 作者邮箱 22 | classifiers=[ 23 | # 'Development Status :: 3 - Alpha', # 当前开发进度等级(测试版,正式版等) 24 | # 'Intended Audience :: Developers', # 模块适用人群 25 | # 'Topic :: Software Development :: Build Tools', # 给模块加话题标签 26 | # 'License :: OSI Approved :: MIT License', # 模块的license 27 | 28 | # 'Programming Language :: Python :: 2', # 模块支持的Python版本 29 | # 'Programming Language :: Python :: 2.7', 30 | 'Programming Language :: Python :: 3', 31 | 'Programming Language :: Python :: 3.4', 32 | 'Programming Language :: Python :: 3.5', 33 | 'Programming Language :: Python :: 3.6', 34 | 'Programming Language :: Python :: 3.7', 35 | ], 36 | keywords='go golang routine thread', # 模块的关键词,使用空格分割 37 | # install_requires=['peppercorn'], # 依赖模块 38 | # extras_require={ # 分组依赖模块,可使用pip install sampleproject[dev] 安装分组内的依赖 39 | # 'dev': ['check-manifest'], 40 | # 'test': ['coverage'], 41 | # }, 42 | # package_data={ # 模块所需的额外文件 43 | # 'sample': ['package_data.dat'], 44 | # }, 45 | # data_files=[('my_data', ['data/data_file'])], # 类似package_data, 但指定不在当前包目录下的文件 46 | # entry_points={ # 新建终端命令并链接到模块函数 47 | # 'console_scripts': [ 48 | # 'sample=sample:main', 49 | # ], 50 | # }, 51 | project_urls={ # 项目相关的额外链接 52 | # 'Bug Reports': 'https://github.com/pypa/sampleproject/issues', 53 | # 'Funding': 'https://donate.pypi.org', 54 | # 'Say Thanks!': 'http://saythanks.io/to/example', 55 | 'Source': 'https://github.com/luoyusang2007/gostyle', 56 | } 57 | ) 58 | -------------------------------------------------------------------------------- /gostyle/_go.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from functools import wraps 3 | from queue import Queue 4 | 5 | 6 | class Chan(Queue): 7 | def __init__(self,**kargs): 8 | super().__init__(**kargs) 9 | def __call__(self,val=None): 10 | if val: 11 | self.put(val) 12 | else: 13 | return self.get() 14 | def __neg__(self): 15 | return self.get() 16 | def __pos__(self): 17 | return self.get() 18 | def __le__(self,val): 19 | self.put(val) 20 | def __lshift__(self,val): 21 | self.put(val) 22 | def __rrshift__(self,val): 23 | self.put(val) 24 | def __iadd__(self,val): 25 | self.put(val) 26 | return self 27 | 28 | def _decorator_attach(daemon = True, forever = False, attached_obj=None, _name=""): 29 | def _decorator_body(f): 30 | nonlocal _name 31 | nonlocal attached_obj 32 | @wraps(f) 33 | def wrapper(*args, **argv): 34 | if forever: 35 | @wraps(f) 36 | def forever_wrapper(*args, **argv): 37 | while True: 38 | f(*args, **argv) 39 | target_thread = threading.Thread(target=forever_wrapper, args=args, kwargs=argv) 40 | else: 41 | target_thread = threading.Thread(target=f, args=args, kwargs=argv) 42 | target_thread.setDaemon(daemon) 43 | target_thread.start() 44 | if attached_obj == "it_self": 45 | attached_obj = f 46 | setattr(attached_obj,_name,wrapper) 47 | return f 48 | elif attached_obj: 49 | if not _name: 50 | _name = f.__name__ 51 | setattr(attached_obj,_name,wrapper) 52 | return f 53 | else: 54 | return wrapper 55 | return _decorator_body 56 | 57 | 58 | # To Support Following Syntax: 59 | # ==================================== 60 | # from package_go import go 61 | # @go.goable() 62 | # def XXXX(arg_1) 63 | # ... 64 | # go.XXXX(arg_1) 65 | # ==================================== 66 | # from package_go import go 67 | # def XXXX(arg_1) 68 | # ... 69 | # go(XXXX)(arg_1) 70 | # ==================================== 71 | class Go: 72 | def __call__(self, func, daemon = True, forever = False): 73 | _decorator_body = _decorator_attach(daemon = daemon, forever = daemon) 74 | return _decorator_body(func) 75 | 76 | def goable(self, daemon = True, forever = False): # Decorator Generator 77 | _decorator_body = _decorator_attach(daemon = daemon, forever = forever, attached_obj=self) # Attach to instance of Go 78 | return _decorator_body 79 | go = Go() 80 | 81 | 82 | 83 | # To Support Following Syntax: 84 | # ==================================== 85 | # import package_go 86 | # @package_go.startable() 87 | # def XXXX(arg_1) 88 | # ... 89 | # XXXX.start(arg_1) 90 | # ==================================== 91 | def startable(daemon = True, forever = False): # Decorator Generator 92 | _decorator_body = _decorator_attach(daemon = daemon, forever = forever, attached_obj="it_self", _name="start") # Attach to function 93 | return _decorator_body 94 | 95 | 96 | # To Support Following Syntax: 97 | # ==================================== 98 | # import package_go 99 | # @package_go.destination() 100 | # def XXXX(arg_1) 101 | # ... 102 | # package_go.to.XXXX(arg_1) 103 | # ==================================== 104 | to = go 105 | def destination(daemon = True, forever = False): # Decorator Generator 106 | _decorator_body = _decorator_attach(daemon = daemon, forever = forever, attached_obj=to) # Attach to function 107 | return _decorator_body 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoStyle 2 | Go syntax implementation in Python. 3 | # Installation 4 | ``` 5 | pip install gostyle 6 | ``` 7 | # Threading Wrapper Like goRoutine 8 | In GoLang, we can create parallel tasks via keyword `go`: 9 | ```go 10 | //GoLang 11 | //... 12 | go XXXX(arg1,arg2) 13 | //... 14 | ``` 15 | In GoLang, the thread creating has following features: 16 | * The parameter passing is the same as the original function defined by user. 17 | * The original function is still usable as defined. 18 | 19 | However, in Python creating a thread is stupid: 20 | ```Python 21 | #Python 22 | #... 23 | t = threading.Thread(target=XXX, args=(arg1,arg2)) 24 | t.start() 25 | #... 26 | ``` 27 | ## Recommended Usage 28 | Usage with best compatibility: 29 | ```Python 30 | import time 31 | from gostyle import go, Chan 32 | chan1 = Chan() 33 | def test_thread(title:str): 34 | for cnt in range(10): 35 | chan1<=cnt 36 | time.sleep(1) 37 | print(title) 38 | def chan_reader(): 39 | while True : 40 | print(chan1()) 41 | # Start the thread 42 | go(test_thread)("Call") 43 | chan_reader() 44 | ``` 45 | 46 | ## How To Use Word `go` in Python 47 | If the function is self-defined, you can use decorator `@gostyle.startable()` like following: 48 | ```Python 49 | import time 50 | import gostyle 51 | @gostyle.startable() 52 | def test_thread(title:str): 53 | while True: 54 | time.sleep(1) 55 | print(title) 56 | # Start the thread 57 | test_thread.start("Start") 58 | # Note that the expression "test_thread('Normal')" can still run the original function in main thread. 59 | ``` 60 | 61 | Or, if the function is not a class/object method: 62 | ```Python 63 | import time 64 | import gostyle 65 | @gostyle.destination() 66 | def test_thread(title:str): 67 | while True: 68 | time.sleep(1) 69 | print(title) 70 | # Start the thread 71 | gostyle.to.test_thread("Go To Destination") 72 | # Note that the expression "test_thread('Normal')" can still run the original function in main thread. 73 | ``` 74 | 75 | Or: 76 | 77 | ```Python 78 | import time 79 | from gostyle import go 80 | @go.goable() 81 | def test_thread(title:str): 82 | while True: 83 | time.sleep(1) 84 | print(title) 85 | # Start the thread 86 | go.test_thread("Go") 87 | # Note that the expression "test_thread('Normal')" can still run the original function in main thread. 88 | ``` 89 | 90 | If the function is not self-defined(you can not add decorator to the function), or the function is a method of a class/object(the function you defined is hard to attach to "go"(same as "to") object in this package), you can use syntax like following: 91 | ```Python 92 | import time 93 | from gostyle import go 94 | def test_thread(title:str): 95 | while True: 96 | time.sleep(1) 97 | print(title) 98 | # Start the thread 99 | go(test_thread)("Call") 100 | ``` 101 | 102 | ## Run-Forever and Daemonize 103 | The `daemon` parameter controls the deamon option in package `threading`. and the forever parameter lets you get rid of a `while True:` expression in the function you defined. 104 | ```Python 105 | import time 106 | from gostyle import go 107 | def test_thread(title:str): 108 | # No Internal WHILE Here. 109 | time.sleep(1) 110 | print(title) 111 | # Start the thread 112 | go(test_thread, forever=True)("Call Forever") 113 | ``` 114 | 115 | ```Python 116 | import time 117 | import gostyle 118 | @gostyle.startable(forever=True) 119 | def test_thread(title:str): 120 | # No Internal WHILE Here. 121 | time.sleep(1) 122 | print(title) 123 | # Start the thread 124 | test_thread.start("Start Loop") 125 | ``` 126 | 127 | # Defer 128 | In GoLang, defer is used to do things(usually cleaning-up) after a function returns. 129 | ## How To Use in Python 130 | Usage of decorator `defer_inside`: 131 | ```Python 132 | from gostyle import defer_inside, defer 133 | @defer_inside 134 | def great_func(): 135 | a = [1,2,3] 136 | b = 8 137 | defer( 138 | lambda : a.append(7), 139 | lambda : print(a), 140 | lambda : print(b) 141 | ) 142 | a.append(9) 143 | return a,b 144 | print(great_func()) 145 | 146 | ``` 147 | 148 | 149 | 150 | ----------------------------------------- 151 | # Todos 152 | ## Threading 153 | Manage Threads started by gostyle 154 | Collect return values 155 | Single Instance support 156 | Yield Support 157 | Multithreading Support 158 | 159 | ## Defer 160 | Multi-times Defer Support 161 | 162 | ## Queue 163 | Queue Wrapper 164 | 165 | ## Switch 166 | ... 167 | 168 | ## Anonymous Functions 169 | ... 170 | 171 | --------------------------------------------------------------------------------