All Projects → pwwang → Python Varname

pwwang / Python Varname

Dark magics about variable names in python

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Python Varname

Debugviewpp
DebugView++, collects, views, filters your application logs, and highlights information that is important to you!
Stars: ✭ 592 (+565.17%)
Mutual labels:  debugging-tool
Lldebugtoolswift
LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
Stars: ✭ 40 (-55.06%)
Mutual labels:  debugging-tool
Autotrace
Runs a process, and gives you the output along with other telemetry on the process, all in one terminal window.
Stars: ✭ 68 (-23.6%)
Mutual labels:  debugging-tool
Lldebugtool
LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
Stars: ✭ 673 (+656.18%)
Mutual labels:  debugging-tool
Pince
A reverse engineering tool that'll supply the place of Cheat Engine for linux
Stars: ✭ 987 (+1008.99%)
Mutual labels:  debugging-tool
Power trace
Buff exception backtrace with local variables, passed in arguments and instance variables!
Stars: ✭ 48 (-46.07%)
Mutual labels:  debugging-tool
Traceur
Easier RxJava2 debugging with better stacktraces
Stars: ✭ 502 (+464.04%)
Mutual labels:  debugging-tool
Strongod
StrongOD(anti anti-debug plugin) driver source code.
Stars: ✭ 76 (-14.61%)
Mutual labels:  debugging-tool
Bugsnag Android
Bugsnag crash monitoring and reporting tool for Android apps
Stars: ✭ 990 (+1012.36%)
Mutual labels:  debugging-tool
Robin
Robin is a logging library for Bundle data passed between Activities and fragments. It also provides a callback to send screen views of user visited pages to your analytics client
Stars: ✭ 63 (-29.21%)
Mutual labels:  debugging-tool
Bugsnag Laravel
Bugsnag notifier for the Laravel PHP framework. Monitor and report Laravel errors.
Stars: ✭ 746 (+738.2%)
Mutual labels:  debugging-tool
Hfsinspect
An open-source HFS+ filesystem explorer and debugger (in the spirit of hfsdebug)
Stars: ✭ 28 (-68.54%)
Mutual labels:  debugging-tool
Bugsnag Node
[DEPRECATED] Please upgrade to our Universal JS notifier "@bugsnag/js" • https://github.com/bugsnag/bugsnag-js
Stars: ✭ 48 (-46.07%)
Mutual labels:  debugging-tool
Bugsnag Js
Javascript error handling tool for Bugsnag. Monitor and report JavaScript bugs & errors.
Stars: ✭ 625 (+602.25%)
Mutual labels:  debugging-tool
Bugsnag Python
Official bugsnag error monitoring and error reporting for django, flask, tornado and other python apps.
Stars: ✭ 69 (-22.47%)
Mutual labels:  debugging-tool
Vuetron
A tool for testing and debugging your Vue + Vuex applications. 是一個可以幫助您 Vue.js 的項目測試及偵錯的工具, 也同時支持 Vuex及 Vue-Router.
Stars: ✭ 531 (+496.63%)
Mutual labels:  debugging-tool
Vim Padre
Debugger plugin for VIM
Stars: ✭ 42 (-52.81%)
Mutual labels:  debugging-tool
Rex Diagnostics
Unity extension that enables expression evaluation at runtime to facilitate testing and debugging.
Stars: ✭ 78 (-12.36%)
Mutual labels:  debugging-tool
Consolewrap
This plugin helps you to work easily with log statements
Stars: ✭ 75 (-15.73%)
Mutual labels:  debugging-tool
Ios Sdk
AppSpector is a debugging service for mobile apps
Stars: ✭ 56 (-37.08%)
Mutual labels:  debugging-tool

varname

Pypi Github PythonVers Building Docs and API Codacy Codacy coverage Chat on gitter

Dark magics about variable names in python

Change Log | API | Playground

Installation

pip install -U varname

Features

  • Core features:

    • Retrieving names of variables a function/class call is assigned to from inside it, using varname.
    • Retrieving variable names directly, using nameof
    • Detecting next immediate attribute name, using will
    • Fetching argument names/sources passed to a function using argname
  • Other helper APIs (built based on core features):

    • A value wrapper to store the variable name that a value is assigned to, using Wrapper
    • A decorator to register __varname__ to functions/classes, using register
    • A debug function to print variables with their names and values

Credits

Thanks goes to these awesome people/projects:


@alexmojaki

executing

Special thanks to @HanyuuLu to give up the name varname in pypi for this project.

Usage

Retrieving the variable names using varname(...)

  • From inside a function

    from varname import varname
    def function():
        return varname()
    
    func = function()  # func == 'func'
    

    When there are intermediate frames:

    def wrapped():
        return function()
    
    def function():
        # retrieve the variable name at the 2nd frame from this one
        return varname(frame=2)
    
    func = wrapped() # func == 'func'
    

    Or use ignore to ignore the wrapped frame:

    def wrapped():
        return function()
    
    def function():
        return varname(ignore=wrapped)
    
    func = wrapped() # func == 'func'
    

    Calls from standard libraries are ignored by default:

    import asyncio
    
    async def function():
        return varname()
    
    func = asyncio.run(function()) # func == 'func'
    
  • Retrieving name of a class instance

    class Foo:
        def __init__(self):
            self.id = varname()
    
        def copy(self):
            # also able to fetch inside a method call
            copied = Foo() # copied.id == 'copied'
            copied.id = varname() # assign id to whatever variable name
            return copied
    
    foo = Foo()   # foo.id == 'foo'
    
    foo2 = foo.copy() # foo2.id == 'foo2'
    
  • Multiple variables on Left-hand side

    # since v0.5.4
    def func():
        return varname(multi_vars=True)
    
    a = func() # a == ('a', )
    a, b = func() # (a, b) == ('a', 'b')
    [a, b] = func() # (a, b) == ('a', 'b')
    
    # hierarchy is also possible
    a, (b, c) = func() # (a, b, c) == ('a', 'b', 'c')
    
  • Some unusual use

    def function():
        return varname()
    
    func = [function()]    # func == ['func']
    
    func = [function(), function()] # func == ['func', 'func']
    
    func = function(), function()   # func = ('func', 'func')
    
    func = func1 = function()  # func == func1 == 'func'
    # a warning will be shown
    # since you may not want func1 to be 'func'
    
    x = func(y = func())  # x == 'x'
    
    # get part of the name
    func_abc = function()[-3:]  # func_abc == 'abc'
    
    # function alias supported now
    function2 = function
    func = function2()  # func == 'func'
    
    a = lambda: 0
    a.b = function() # a.b == 'b'
    
    # Since v0.1.3
    # We can ask varname to raise exceptions
    # if it fails to detect the variable name
    def get_name(raise_exc):
        return varname(raise_exc=raise_exc)
    
    a = {}
    a['b'] = get_name(True) # VarnameRetrievingError
    a['b'] = get_name(False) # None
    

The decorator way to register __varname__ to functions/classes

  • Registering __varname__ to functions

    from varname.helpers import register
    
    @register
    def function():
        return __varname__
    
    func = function() # func == 'func'
    
    # arguments also allowed (frame, ignore and raise_exc)
    @register(frame=2)
    def function():
        return __varname__
    
    def wrapped():
        return function()
    
    func = wrapped() # func == 'func'
    
  • Registering __varname__ as a class property

    @register
    class Foo:
        ...
    
    foo = Foo()
    # foo.__varname__ == 'foo'
    

Getting variable names directly using nameof

from varname import varname, nameof

a = 1
nameof(a) # 'a'

b = 2
nameof(a, b) # ('a', 'b')

def func():
    return varname() + '_suffix'

f = func() # f == 'f_suffix'
nameof(f)  # 'f'

# get full names of (chained) attribute calls
func.a = func
nameof(func.a, vars_only=False) # 'func.a'

func.a.b = 1
nameof(func.a.b, vars_only=False) # 'func.a.b'

Detecting next immediate attribute name

from varname import will
class AwesomeClass:
    def __init__(self):
        self.will = None

    def permit(self):
        self.will = will(raise_exc=False)
        if self.will == 'do':
            # let self handle do
            return self
        raise AttributeError('Should do something with AwesomeClass object')

    def do(self):
        if self.will != 'do':
            raise AttributeError("You don't have permission to do")
        return 'I am doing!'

awesome = AwesomeClass()
awesome.do() # AttributeError: You don't have permission to do
awesome.permit() # AttributeError: Should do something with AwesomeClass object
awesome.permit().do() == 'I am doing!'

Fetching argument names/sources using argname

from varname import argname

def func(a, b=1):
    print(argname(a))

x = y = z = 2
func(x) # prints: x

def func2(a, b=1):
    print(argname(a, b))
func2(y, b=x) # prints: ('y', 'x')

# allow expressions
def func3(a, b=1):
    print(argname(a, b, vars_only=False))
func3(x+y, y+x) # prints: ('x+y', 'y+x')

# positional and keyword arguments
def func4(*args, **kwargs):
    print(argname(args[1], kwargs['c']))
func4(y, x, c=z) # prints: ('x', 'z')

Value wrapper

from varname.helpers import Wrapper

foo = Wrapper(True)
# foo.name == 'foo'
# foo.value == True
bar = Wrapper(False)
# bar.name == 'bar'
# bar.value == False

def values_to_dict(*args):
    return {val.name: val.value for val in args}

mydict = values_to_dict(foo, bar)
# {'foo': True, 'bar': False}

Debugging with debug

from varname.helpers import debug

a = 'value'
b = object()
debug(a) # DEBUG: a='value'
debug(b) # DEBUG: b=<object object at 0x2b70580e5f20>
debug(a, b)
# DEBUG: a='value'
# DEBUG: b=<object object at 0x2b70580e5f20>
debug(a, b, merge=True)
# DEBUG: a='value', b=<object object at 0x2b70580e5f20>
debug(a, repr=False, prefix='') # a=value
# also debug an expression
debug(a+a) # DEBUG: a+a='valuevalue'
# If you want to disable it:
debug(a+a, vars_only=True) # error

Reliability and limitations

varname is all depending on executing package to look for the node. The node executing detects is ensured to be the correct one (see this).

It partially works with environments where other AST magics apply, including pytest, ipython, macropy, birdseye, reticulate with R, etc. Neither executing nor varname is 100% working with those environments. Use it at your own risk.

For example:

  • This will not work with pytest:
    a = 1
    assert nameof(a) == 'a' # pytest manipulated the ast here
    
    # do this instead
    name_a = nameof(a)
    assert name_a == 'a'
    
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].