Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python vars() Function

#1
Python vars() Function

Python’s built-in vars() function returns the __dict__ attribute of an object—a dictionary containing the object’s changeable attributes. Without argument, it returns the local symbol table similar to locals().

class Car: def __init__(self): self.speed = 100 self.brand = 'porsche' porsche = Car()
print(vars(porsche))
# {'speed': 100, 'brand': 'porsche'}

Python’s built-in vars() function returns a dictionary of name: value mappings of all the names defined in the local scope or the scope of the optional object argument, and their associated values.

  • When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.
  • When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.
Python vars() Function - Explanation + Examplehttps://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" />

Learn by example! Here’s an example on how to use the vars() built-in function.

Video vars()




vars() without Argument: Syntax and Example


Syntax: 
vars() # Returns dictionary of "name --> value" mappings like locals()

Arguments -
Return Value dict Dictionary of mappings from variable names defined in the local namespace and the objects they’re referring to.

When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> vars() == locals()
True

vars() with Argument: Syntax and Example


Syntax: 
vars(object) # Returns same as object.__dict__()

Arguments object Object for which the attribute name-object mappings should be retrieved
Return Value dict Dictionary of mappings from attribute names defined in the object’s namespace and the objects they’re referring to.

When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.

>>> def f(): x = 2 >>> vars(f)
{}
>>> f.y = 42
>>> vars(f)
{'y': 42}

As soon as you assign a new attribute y to the function object, it becomes available in the dictionary returned by the vars() function. However, the local variable x is not an attribute of f, so it is not part of the returned dictionary.

[How to Fix] TypeError: vars() argument must have __dict__ attribute


If you pass an argument into the vars() function that doesn’t have a __dict__() function, Python raises a TypeError. This means that the object in question doesn’t have any attributes such as an integer, float, list, etc.

>>> vars(42)
Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> vars(42)
TypeError: vars() argument must have __dict__ attribute

You can fix it by only passing arguments that have overwritten the __dict__ method such as a function or a custom object:

>>> def f(): return 42 >>> vars(f)
{}
>>> f.val = 'YES'
>>> vars(f)
{'val': 'YES'}

Summary


Python’s built-in vars() function returns a dictionary of name: value mappings of all the names defined in the local scope or the scope of the optional object argument, and their associated values.

When used without an argument, vars() returns the same as locals() that returns a dictionary of name --> object mappings of names defined in the current local scope and objects being their associated values.

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\...\\code.py', 'find_path': <function find_path at 0x0000019B33898730>, 'G': [[1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]}
>>> vars() == locals()
True

When used with an object argument, vars(object) returns the same as object.__dict__() that returns a dictionary of name --> object mappings of writable names defined in the object’s scope and objects being their associated values.

>>> def f(): x = 2 >>> vars(f)
{}
>>> f.y = 42
>>> vars(f)
{'y': 42}

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post Python vars() Function first appeared on Finxter.



https://www.sickgaming.net/blog/2021/02/...-function/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Get Milliseconds xSicKxBot 0 41 02-19-2021, 08:28 AM
Last Post: xSicKxBot
  [Tut] Python object() Function xSicKxBot 0 42 02-16-2021, 08:16 PM
Last Post: xSicKxBot
  [Tut] Python repr() Function — A Helpful Guide with Example xSicKxBot 0 44 02-15-2021, 02:40 PM
Last Post: xSicKxBot
  [Tut] Python str() Function xSicKxBot 0 39 02-14-2021, 06:05 AM
Last Post: xSicKxBot
  [Tut] Python issubclass() xSicKxBot 0 43 02-12-2021, 10:40 AM
Last Post: xSicKxBot
  [Tut] Python int() Function xSicKxBot 0 47 02-04-2021, 08:21 PM
Last Post: xSicKxBot
  [Tut] How To Cut A String In Python? xSicKxBot 0 36 02-01-2021, 04:09 PM
Last Post: xSicKxBot
  [Tut] Python filter() xSicKxBot 0 57 02-01-2021, 03:25 AM
Last Post: xSicKxBot
  [Tut] How to Chain Multiple Function Calls in Python? xSicKxBot 0 38 01-27-2021, 05:47 PM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 41 01-22-2021, 01:02 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
Unreal Engine Coming To A Cloud Near You
Last Post: xSicKxBot
Today 09:39 AM
» Replies: 0
» Views: 2
[Tut] Python iter() — A Simple Illustrat...
Last Post: xSicKxBot
Today 12:28 AM
» Replies: 0
» Views: 4
(Indie Deal) Warhammer: Chaosbane, WRC 9...
Last Post: xSicKxBot
Today 12:28 AM
» Replies: 0
» Views: 5
News - Introducing the Bungie Tech Blog
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 6
News - Atlus Wants To Know What Games Yo...
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 5
Xbox Wire - Halo Infinite – Inside Infin...
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 5
News - Blog: Six examples of UI worth st...
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 5
News - Get a job: Join Housemarque as a ...
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 5
News - Control Dev Remedy Entertainment ...
Last Post: xSicKxBot
Today 12:27 AM
» Replies: 0
» Views: 9
Monster Mash Sketch Based Modelling and ...
Last Post: xSicKxBot
Yesterday 03:55 PM
» Replies: 0
» Views: 4

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020