Attribute (programming)

In object-oriented programming, an attribute is a specification that defines a property of an object, element, or file. It may also refer to or set the specific value for a given instance of such. For clarity, attributes should more correctly be considered metadata. An attribute is frequently and generally a property of a property. However, in actual usage, the term attribute can and is often treated as equivalent to a property depending on the technology being discussed. An attribute of an object usually consists of a name and a value. For an element these can be a type and class name, while for a file these can be a name and an extension, respectively.

In object-oriented programming, classes can contain attributes and methods.
An attribute in a relational database can be represented as a column or field.

Rules and typing

edit
  • Rules: Each named attribute has an associated set of rules called operations: For example, one doesn't sum characters or manipulate and process an integer array the same way as an image object. Neither does one process text as if it was type of floating point (decimal numbers).
  • Data types: It follows that an object definition can be extended by imposing data typing which can consist of a representation format, a default value, and legal operations (rules) and restrictions (e.g. "division by zero is not to be tolerated") are all potentially involved in defining an attribute, or conversely one may view them as attributes of that object's type.

Picture file formats (for example JPEG, PNG and BMP) are not decoded using the same operations (however similar the images look these are all graphics data formats). Similarly, a programming language does not use the same operations to evaluate a floating point typed number and typed long integers.

For example, in computer graphics, line objects can have attributes such as thickness (with real values), color (with descriptive values such as brown or green or values defined in a certain color model, such as RGB), dashing attributes, etc. A circle object can be defined in similar attributes plus an origin and radius. In reference to computer systems, attributes are defined particularly for read or write attributes for specific read or write.

Attribute usage

edit

If the element in question could be considered a property (CUSTOMER_NAME) of another entity (let's say CUSTOMER), the element can have zero or more attributes (properties) of its own (CUSTOMER_NAME is of TYPE = "KINDOFTEXT").

C introduced attributes in C23, following that of C++11.[1]

[[nodiscard]]
int add(int a, int b, [[maybe_unused]] int c) {
    return a + b;
}

C++ has support for both attributes and annotations.

C++11 added attributes, which are indicators to the compiler of some information. However, they are either standard-defined or implementation-defined, and custom attributes cannot be created.[2]

class Integer {
private:
    [[no_unique_address]] 
    int x;
public:
    [[nodiscard]]
    bool isPositive() const noexcept {
        if (x > 0) [[likely]] {
            return true;
        }
        return false;
    }
};

C++26 added annotations which can be created, and can be accessed using reflection, allowing arbitrary metadata to be attached.[3]

import std;

using std::string;

// some annotations defined in namespace wikipedia::examples
using wikipedia::examples::Debug;
using wikipedia::examples::EnumFlag;
using wikipedia::examples::Rename;

enum class [[=EnumFlag]] Toggle: uint8_t {
    Off, 
    On
};

struct [[=Debug]] Person {
    [[=Rename("full name")]] 
    string fullName;
    int age;
};

In the C# programming language, attributes are metadata attached to a field or a block of code like assemblies, members and types, and are equivalent to annotations in Java.[4] Attributes are accessible to both the compiler and programmatically through reflection. In contrast, properties, in C# terminology, are members of a class which syntactically are used like instance (or class) variables, but are implemented as a pair of getter/setter functions. (In the absence of a setter, properties are read-only.)

Users of the language see many examples where attributes are used to address cross-cutting concerns and other mechanistic or platform uses. This creates the false impression that this is their sole intended purpose.

Their specific use as metadata is left to the developer and can cover a wide range of types of information about any given application, classes and members that is not instance-specific. The decision to expose any given attribute as a property is also left to the developer as is the decision to use them as part of a larger application framework.

Attributes are implemented as classes that are derived from System.Attribute. They are often used by the CLR services, like COM interoperability, remoting, serialisation and can be queried at runtime.

The example shows how attributes are defined in C#:

// causes compiler message saying that 
[Obsolete("Use class NewClass instead", IsError = true)]
public class ObsoleteClass
{
    // ...
}

public class NewClass
{
    // ...
}

// class name ends with "Attribute"
// but can be used as "Obsolete"
public class ObsoleteAttribute : Attribute 
{
    public string Message { get; }
    public bool IsError { get; set; }
    public ObsoleteAttribute() {...}
    public ObsoleteAttribute(string msg) {...}
    public ObsoleteAttribute(string msg, bool error) {...}
}

[Obsolete]
[Obsolete("This is obsolete")]
[Obsolete("This is obsolete", false)]
[Obsolete("This is obsolete", IsError = false)]

Positional parameters like first parameter of type string above are parameters of the attribute's constructor. Name parameters like the Boolean parameter in the example are a property of the attribute and should be a constant value.[5]

Attributes should be contrasted against XML documentation that also defines metadata, but is not included in the compiled assembly and therefore cannot be accessed programmatically.

HTML & JavaScript

edit

Display the checked attribute and property of a checkbox as it changes.

<!doctype html>
<html>
<body>

<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>

<script>
  document.getElementById('check1').addEventListener('change', function(e) {
    var input = this;
    var p = document.querySelector('p');
    
    p.innerHTML = 
      "input.checked: <b>" + (input.checked ? 'true' : 'false') + "</b>"
  });
</script>
</body>
</html>

Java

edit

The Java language uses annotations to carry metadata on symbols or perform code generation, and can be accessed using reflection.[6]

abstract class Animal {
    public abstract void speak();

    public String getType() {
        return "Generic animal";
    }
}

class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("Meow!");
    }

    @Override
    public String getType() {
        return "Cat";
    }
}

Multi-valued databases

edit

On many post-relational or multi-valued databases systems, relative to SQL, tables are files, rows are items, and columns are attributes. Both in the database and code, attribute is synonymous with property and variable although attributes can be further defined to contain values and subvalues.

The first of these databases was the Pick operating system. Two current platforms include Rocket U2's Universe and InterSystems' Caché.

Python

edit

In Python, attributes are called decorators, which are any callable that can extend or modify another function, variable or class without changing its source code.[7] A decorator is denoted with @, and appears above the declaration.

from functools import wraps
from typing import Any, Callable, TypeVar

T = TypeVar("T")

def log_call(func: Callable[..., T]) -> Callable[..., T]:
    @wraps(func)
    def wrapper(*args: tuple[int, ...], **kwargs: dict[str, str]) -> T:
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        return: T = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_call
def add(a: int, b: int) -> int:
    return a + b

@log_call
def greet(name: str) -> str:
    return f"Hello, {name}!"

Rust

edit

In Rust, the syntax of an attribute is #[attr], placed on any symbol, or even statements. Attributes modify how code is compiled or behaves by attaching metadata to a symbol. In Rust, attributes are a type of procedural macro, which acts on Rust syntax by consuming and producing code.[8]

Many macros are defined in the language, but new ones are created using procedural macros. The following are some examples of usage of existing macros:[9]

// Marks a function as inline
#[inline]
fn add(a: i32, b: i32) -> i32 {
    a + b
}

// Allows unused variables
#[allow(unused_variables)]
fn example() {
    let x = 5;
}

// Conditionally compiles the function if the platform is Windows
#[cfg(target_os = "windows")]
fn windows_only() {
    println!("Running on Windows.");
}

Rust also supports the #[derive(Ts...)], which are called "derive macros", used to automatically implement traits.

// Point automatically implements traits Debug, Clone, PartialEq
#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

Swift

edit

In Swift, attributes are denoted with the @ character, and indicate additional metadata to the compiler. They can be grouped into declaration attributes, type attributes, property wrappers, concurrency attributes, and interface builder attributes.[10]

@available(iOS 17, *)
func newFeature() {
    print("Only available on iOS 17+")
}

In XML, an attribute is a markup construct consisting of a name/value pair that exists within a start-tag or empty-element tag. Markup languages, such as HTML and XML, use attributes to describe data and the formatting of data.

A good example is the process of XML assigning values to properties (elements). Note that the element's value is found before the (separate) end tag, not in the element itself. The element itself may have a number of attributes set (NAME = "IAMAPROPERTY").

If the element in question could be considered a property (CUSTOMER_NAME) of another entity (let's say CUSTOMER), the element can have zero or more attributes (properties) of its own (CUSTOMER_NAME is of TYPE = "KINDOFTEXT").

See also

edit

References

edit
  1. cppreference.com. "Attribute specifier sequence (since C23)". cppreference.com. cppreference.com. Retrieved 3 May 2026.
  2. cppreference.com. "Attribute specifier sequence (since C++11)". cppreference.com. cppreference.com. Retrieved 1 May 2026.
  3. Wyatt Childers, Dan Katz, Barry Rezvin, Daveed Vandevoorde (19 June 2025). "Annotations for Reflection". isocpp.org. WG21.{{cite web}}: CS1 maint: multiple names: authors list (link)
  4. Microsoft Learn (19 March 2025). "Attributes". learn.microsoft.com. Microsoft Learn.
  5. Mössenböck, Hanspeter (2002-03-25). "Advanced C#: Variable Number of Parameters" (PDF). Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik. p. 44. Retrieved 2011-08-08.
  6. "Annotations". Sun Microsystems. Archived from the original on 2011-09-25. Retrieved 2011-09-30.
  7. Python Software Foundation (7 April 2026). "Glossary - decorator". docs.python.org. Python Software Foundation.
  8. The Rust Team (16 April 2026). "Procedural Macros - The Rust Reference". doc.rust-lang.org. The Rust Team.
  9. The Rust Team (16 April 2026). "Attributes - The Rust Reference". doc.rust-lang.org. The Rust Team.
  10. Apple Inc. "Attributes". docs.swift.org. Apple Inc. Retrieved 8 May 2026.