What is the proper way to bundle variables in python

I have three variables that are closely tied together and I do not want to pass separately every time I call a function. What is the proper way to bundle them.

Context: The purpose of the variables is to keep track of some properties of a document while I am reading it word by word.

My current approach is to bundle them in a class:

class MarkdownIsOpen(object):
    def __init__(self):
        self.ChapterOpen = False
        self.SectionOpen = False
        self.ArticleOpen = False

But this seems a bit wrong to me, as I do not intend to add any methods or other functionalities.

A namedtuple would be perfect if it were mutable.

What would be the proper (most pythonic) way to bundle the three variables?

Use a dataclass:

@dataclass
class MarkdownIsOpen:
    ChapterOpen: bool = False
    SectionOpen: bool = False
    ArticleOpen: bool = False

Or:

MarkdownIsOpen = make_dataclass('MarkdownIsOpen', ['ChapterOpen', 'SectionOpen', 'ArticleOpen'])

Note that this requires Python 3.7.

If you're using Python <= 3.6, then an ordinary class will do as well. Classes are not expensive, and they provide a hint to the user that your function does not expect any old dict-like, but a special container with the following attributes.

Compare this to, for example, C's struct or Scala's case class, which serve largely the same purpose.

Also, you can even override __slots__ and/or __getitem__ to allow dict-like access, and prevent the addition of new attributes:

class MarkdownIsOpen:

    __slots__ = ('ChapterOpen', 'SectionOpen', 'ArticleOpen')

    def __init__(self):
        self.ChapterOpen = False
        self.SectionOpen = False
        self.ArticleOpen = False

    def __getattr__(self, key):
        return getattr(self, key)

    def __setattr__(self, key, value):
        setattr(self, key, value)

Example:

m = MarkdownIsOpen()
m['ChapterOpen'] = True
print(m['SectionOpen'])
m['Nonexistent'] = False

Output:

False
AttributeError: 'MarkdownIsOpen' object has no attribute 'Nonexistent'

Programming FAQ — Python 3.8.5 documentation, How do I share global variables across modules? What are the “best practices” for using import in a module? Or bundle up values in a class instance: >>> Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context".

You can use dataclasses.

@dataclass
class MarkdownIsOpen:
    ChapterOpen: bool = False
    SectionOpen: bool = False
    ArticleOpen: bool = False

9. Classes — Python 3.8.5 documentation, Classes provide a means of bundling data and functionality together. The global statement can be used to indicate that particular variables live in the However, it is not necessary to call a method right away: x.f is a method object, and can� That’s right, your Figure will have four axes in total, arranged in a structure that has two rows and two columns. With the line of code that you have considered, you say that the variable ax is the first of the four axes to which you want to start plotting.

May take a look at this question: Existence of mutable named tuple in Python?

With two nice answers: recordclass and namedlist of mutable alternatives to named tuples

Four ways to assign variables in Python — Reuven Lerner, That's right; the result of invoking “globals” is not only a dictionary showing us all of the global variables, but is something we can modify — and� I don't want to package the Frameworks in with Blender and redistribute the whole app. I don't want to set environment variables. I want to make a single folder that can be added to a site-packages folder inside either the console Python or the Blender Python install and just have it work out of the box.

You could use a simple named tuple or a simple dictionary for that purpose, if you really never need to define any methods on the class.

15. Classes and Objects — the Basics — How to Think Like a , A natural way to represent a point in Python is with two numeric values. The variables p and q are assigned references to two new Point objects. production line, its initialization method is executed to get the object properly set up with It bundles together the data and the operations that are relevant for that kind of data. In Python 2.4 and earlier, if you’re reading a module located inside a package, it is not clear whether import foo refers to a top-level module or to another module inside the package. As Python’s library expands, more and more existing package internal modules suddenly shadow standard library modules by accident.

(Tutorial) Python Functions, A tutorial on functions in Python that covers how to write functions, how to call to a Python Function; Function Arguments in Python; Global vs Local Variables You use functions in programming to bundle a set of instructions that you call and in precisely the right order, just like in the following example:. The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72). The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses.

Chapter 4 – Lists, the book/ebook bundle directly from No Starch Press. Then I'll briefly cover the list-like tuple and string data types and how they compare to list values. A list value stored in the variable spam , showing which value each index refers to The proper way to “mutate” a string is to use slicing and concatenation to build a � To test multiple variables x, y, z against a value in Python, use the expression value in {x, y, z}.Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.

Python Tutorial, List: Python supports variable-size dynamic array via a built-in data structure called list The string on which this method is called can contain literal text or We use str class' member function rstrip() to strip the trailing (right) white spaces; and and bundled with commonly-used packages (such as NumPy, Matplotlib and� set PYTHONPATH = /usr/local/lib/python Namespaces and Scoping. Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

Comments
  • Can you give an example of a function call with these variables and what you wish to do exactly ?
  • A dictionary would be simple.
  • Use namedtuples, that's probably the best fit for this.
  • I loved this one: stackoverflow.com/a/18792190/6198978
  • I'm not sure to understand the advantage of this over a simple namedtuple, even the PEP doesn't convince me (unless if you need to have static type verification, which doesn't seem to be the case here). I would still suggest to use namedtuple for this.
  • If you like to use dataclasses approach then may be better to write: MarkdownIsOpen = make_dataclass('MarkdownIsOpen', ['ChapterOpen', 'SectionOpen', 'ArticleOpen']).
  • @cglacet OP mentioned that mutability is necessary, which rules out namedtuple. I am actually quite a big fan of namedtuple, but one problem I have with it is allowing numerical indexed access.
  • Thank you for the suggestions. I will go for the dataclass though because that is from the standard library.
  • namedtuple also are in the standard library